Merge pull request #424 from filecoin-project/@akuokojnr/unity-integration

feat: display unity game in slate
This commit is contained in:
CAKE 2020-11-17 20:24:41 -08:00 committed by GitHub
commit e39ec32fc6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 60 additions and 0 deletions

View File

@ -2,6 +2,8 @@ import * as React from "react";
import * as Constants from "~/common/constants";
import * as Validations from "~/common/validations";
import UnityFrame from "~/components/core/UnityFrame";
import { css } from "@emotion/core";
const STYLES_FAILURE = css`
@ -92,6 +94,10 @@ export default class SlateMediaObject extends React.Component {
);
}
if (type.startsWith("application/")) {
return <UnityFrame url={url} />;
}
return element;
}
}

View File

@ -0,0 +1,54 @@
import * as React from "react";
import { css } from "@emotion/core";
const STYLES_CONTAINER = css`
height: 100%;
width: 100%;
`;
const loadScript = (url) =>
new Promise((res, rej) => {
// NOTE (Amine): Create script
const script = document.createElement("script");
script.src = url;
document.body.appendChild(script);
script.onload = () => res(script);
});
const UnityFrame = ({ url }) => {
const unityInstance = React.useRef();
const [isLoading, setLoadingStatus] = React.useState(true);
// NOTE (daniel): url to unity game root
const gameRootUrl = url.split("/index.html")[0];
const _loadScripts = async () => Promise.all([loadScript(`${gameRootUrl}/Build/UnityLoader.js`)]);
const _cleanScripts = () => {
const scripts = document.getElementsByTagName("script");
const unityLoaderRegex = new RegExp(/UnityLoader.js/);
Array.from(scripts).forEach((script) => {
if (unityLoaderRegex.test(script.src)) {
script.remove();
}
});
};
React.useEffect(() => {
_loadScripts().then(() => {
if (window) {
unityInstance.current = window.UnityLoader.instantiate(
"unityContainer",
`${gameRootUrl}/Build/WebGL%20Repo.json`
);
setLoadingStatus(false);
}
});
return _cleanScripts;
}, []);
return <div id="unityContainer" css={STYLES_CONTAINER} />;
};
export default UnityFrame;