This project demonstrates how to integrate a Unity WebGL build into a React application using the react-unity-webgl package.
- A Unity project set up to build for WebGL.
- Node.js and npm (or yarn) installed.
- A React project (this setup assumes you are using Create React App or a similar setup).
- Open your Unity project.
- Go to File > Build Settings... and select WebGL as the platform.
- Click Build and choose an output folder (e.g.,
Build).
The Unity WebGL build output folder may contain several .gz files. These gzipped files are automatically handled by your web server if properly configured. However, if you need to extract these files manually:
- Locate the
.gzfiles inside yourBuildfolder. - Use an extraction tool (e.g., 7-Zip on Windows or the built-in tools on macOS/Linux) to unzip these files.
- Verify that you now have the extracted
.data,.js, and.wasmfiles.
- In your React project, locate the
publicfolder. - Copy the entire
Buildfolder (with the extracted files) into your React app’spublicdirectory. The structure should look like this:
your-react-app/
├── public/
│ └── Build/
│ ├── FirstWebGL.loader.js
│ ├── FirstWebGL.data
│ ├── FirstWebGL.framework.js
│ └── FirstWebGL.wasm
└── app/
└── components/
└── UnityGame.tsxMake sure your UnityGame.tsx file (located in app/components) points to the correct Unity WebGL build files. Below is an example implementation:
import React from "react";
import { Unity, useUnityContext } from "react-unity-webgl";
export function UnityGame() {
const { unityProvider } = useUnityContext({
loaderUrl: "Build/FirstWebGL.loader.js",
dataUrl: "Build/FirstWebGL.data",
frameworkUrl: "Build/FirstWebGL.framework.js",
codeUrl: "Build/FirstWebGL.wasm",
});
return (
<div style={{ width: "100%", height: "100%" }}>
<Unity unityProvider={unityProvider} />
</div>
);
}-
In the root directory of your React project, install the dependencies if you haven’t already:
npm install
-
Start the development server:
npm run dev
-
Open your web browser and navigate to http://localhost:5173. You should see your Unity WebGL content rendered within your React application. Project Structure Example
Below is an example of what your project structure might look like with the updated location for the UnityGame component:
your-react-app/
├── public/
│ ├── index.html
│ └── Build/
│ ├── FirstWebGL.loader.js
│ ├── FirstWebGL.data
│ ├── FirstWebGL.framework.js
│ └── FirstWebGL.wasm
├── app/
│ └── components/
│ └── UnityGame.tsx
├── src/
│ ├── App.tsx
│ └── index.tsx
├── package.json
└── README.md