React Unity WebGL
Bringing your Unity Games to the Web since 2017!
When bringing your Unity Application to the web, you might need to communicate with Components on a webpage, build interactive interfaces or might want to implement functionality using Web APIs which Unity does not expose. Combining Unity with React is a great way to achieve these goals. React Unity WebGL provides a modern solution for embedding Unity WebGL builds in your React Application while providing advanced APIs for two way communication and interaction between Unity and React.
% npm install react-unity-webgl
- Hello World
- Loading State
- Communication
A basic example showing how to embed a Unity WebGL build in your React Application.
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
return <Unity unityProvider={unityProvider} />;
}
An example showing how to use the Unity Context to provide a loading state.
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const { unityProvider, loadingProgression, isLoaded } = useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
return (
<Fragment>
{!isLoaded && (
<p>Loading Application... {Math.round(loadingProgression * 100)}%</p>
)}
<Unity
unityProvider={unityProvider}
style={{ visibility: isLoaded ? "visible" : "hidden" }}
/>
</Fragment>
);
}
An advanced example showing how to use the Unity Context to communicate between Unity and React.
import React, { Fragment } from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
function App() {
const [isGameOver, setIsGameOver] = useState(false);
const [userName, setUserName] = useState();
const [score, setScore] = useState();
const { unityProvider, sendMessage, addEventListener, removeEventListener } =
useUnityContext({
loaderUrl: "build/myunityapp.loader.js",
dataUrl: "build/myunityapp.data",
frameworkUrl: "build/myunityapp.framework.js",
codeUrl: "build/myunityapp.wasm",
});
const handleGameOver = useCallback((userName, score) => {
setIsGameOver(true);
setUserName(userName);
setScore(score);
}, []);
useEffect(() => {
addEventListener("GameOver", handleGameOver);
return () => {
removeEventListener("GameOver", handleGameOver);
};
}, [addEventListener, removeEventListener, handleGameOver]);
function handleClickSpawnEnemies() {
sendMessage("GameController", "SpawnEnemies", 100);
}
return (
<Fragment>
<Unity unityProvider={unityProvider} />
<button onClick={handleClickSpawnEnemies}>Spawn Enemies</button>
{isGameOver === true && (
<p>{`Game Over ${userName}! You've scored ${score} points.`}</p>
)}
</Fragment>
);
}