slate/components/core/UnityFrame.js

53 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-11-17 15:53:15 +03:00
import * as React from "react";
2020-11-30 08:24:22 +03:00
import { css } from "@emotion/react";
2020-11-17 21:22:13 +03:00
const STYLES_CONTAINER = css`
height: 100%;
width: 100%;
`;
2020-11-23 19:21:13 +03:00
const _loadScript = (url) =>
2020-11-17 15:53:15 +03:00
new Promise((res, rej) => {
// NOTE (Amine): Create script
const script = document.createElement("script");
script.src = url;
document.body.appendChild(script);
script.onload = () => res(script);
});
2020-11-23 19:21:13 +03:00
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();
}
});
};
2020-11-17 15:53:15 +03:00
const UnityFrame = ({ url, unityGameLoader, unityGameConfig }) => {
2020-11-17 15:53:15 +03:00
React.useEffect(() => {
2020-11-23 19:21:13 +03:00
let unityInstance;
2020-12-18 01:47:04 +03:00
_loadScript(`${url}/${unityGameLoader}`).then(() => {
2020-11-17 15:53:15 +03:00
if (window) {
2020-11-23 19:21:13 +03:00
unityInstance = window.UnityLoader.instantiate(
2020-11-17 15:53:15 +03:00
"unityContainer",
2020-12-18 01:47:04 +03:00
`${url}/${unityGameConfig}`
2020-11-17 15:53:15 +03:00
);
}
});
2020-11-23 19:21:13 +03:00
return () => {
// NOTE (Amine): clean up Unity events on unmout
if (unityInstance) {
unityInstance.Quit();
}
_cleanScripts();
};
2020-11-17 15:53:15 +03:00
}, []);
2020-11-17 21:22:13 +03:00
return <div id="unityContainer" css={STYLES_CONTAINER} />;
2020-11-17 15:53:15 +03:00
};
export default UnityFrame;