求助:如何将已完成的Unity项目集成到React组件中
Hey there! Integrating a Unity WebGL build into a React app is totally manageable—let’s break down the process step by step, building on what you’ve already done (copying the /unity/ folder into your component directory):
First, Double-Check Your Unity Build
Before diving into React, make sure your Unity project is exported as a WebGL build:
- Open your Unity project, go to
File > Build Settings - Select
WebGLas the platform, clickSwitch Platform - Configure build settings (enable compression, optimize for web) then click
Build - Ensure the output files (the
Build/folder,TemplateData/folder, and associated scripts) are all inside your/unity/directory
Option 1: Native Integration (No Third-Party Libraries)
If you prefer to avoid extra dependencies, you can load Unity directly in your React component using vanilla JS:
Adjust Your Folder Structure
If you’re using Create React App or Vite, move your/unity/folder to the project’spublic/directory. This ensures React serves the Unity files as static assets (files insrc/get processed by webpack, which can break Unity’s loader).Create the React Component
Use a ref to target a container div, then dynamically load Unity’s loader script and initialize the instance:import { useEffect, useRef } from 'react'; const UnityEmbed = () => { const unityContainer = useRef(null); useEffect(() => { // Load Unity's loader script const loaderScript = document.createElement('script'); loaderScript.src = '/unity/TemplateData/UnityLoader.js'; loaderScript.onload = () => { // Initialize the Unity instance window.unityInstance = UnityLoader.instantiate( 'unity-container', '/unity/Build/YourProjectName.json', // Replace with your actual build JSON filename { onProgress: (progress) => { console.log(`Unity loading: ${Math.round(progress * 100)}%`); } } ); }; document.body.appendChild(loaderScript); // Cleanup on component unmount return () => { if (window.unityInstance) { window.unityInstance.Quit(); } loaderScript.remove(); }; }, []); return ( <div id="unity-container" ref={unityContainer} style={{ width: '800px', height: '600px', border: '1px solid #ccc' }} /> ); }; export default UnityEmbed;
Option 2: Use a React Unity Library (Simpler)
For a more streamlined experience, use the @asmadsen/react-unity-webgl library—it handles most of the boilerplate for you:
Install the Library
npm install @asmadsen/react-unity-webgl # or yarn add @asmadsen/react-unity-webglBuild Your Component
import { Unity, useUnityContext } from '@asmadsen/react-unity-webgl'; const UnityEmbed = () => { const { unityProvider, loadingProgression } = useUnityContext({ loaderUrl: '/unity/TemplateData/UnityLoader.js', dataUrl: '/unity/Build/YourProjectName.data', frameworkUrl: '/unity/Build/YourProjectName.framework.js', codeUrl: '/unity/Build/YourProjectName.wasm', }); // Show loading progress if (loadingProgression < 1) { return <div>Loading Unity: {Math.round(loadingProgression * 100)}%</div>; } return ( <Unity unityProvider={unityProvider} style={{ width: '800px', height: '600px' }} /> ); }; export default UnityEmbed;
Common Pitfalls to Watch For
- Path Errors: Double-check all file paths—if you’re using a custom React setup, ensure your server serves the
/unity/folder as static content. - CORS Issues: When deploying, make sure your hosting platform (Netlify, Vercel, etc.) allows access to the Unity WASM and data files. Most platforms handle this automatically, but if you see CORS errors, adjust your server config.
- Performance: Enable Unity’s WebGL compression (Gzip or Brotli) to reduce build size and load time. You can set this in Unity’s
Player Settings > Publishing Settings. - React-Unity Communication: If you need to pass data between React and Unity, use
SendMessagein the native approach, or thesendmethod provided byreact-unity-webgl. For example, in React you’d callunityContext.send("MyGameObject", "MyUnityMethod", "Hello from React!").
内容的提问来源于stack exchange,提问作者Nicolás Riccardi

