You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何将已完成的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 WebGL as the platform, click Switch 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:

  1. Adjust Your Folder Structure
    If you’re using Create React App or Vite, move your /unity/ folder to the project’s public/ directory. This ensures React serves the Unity files as static assets (files in src/ get processed by webpack, which can break Unity’s loader).

  2. 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:

  1. Install the Library

    npm install @asmadsen/react-unity-webgl
    # or
    yarn add @asmadsen/react-unity-webgl
    
  2. Build 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 SendMessage in the native approach, or the send method provided by react-unity-webgl. For example, in React you’d call unityContext.send("MyGameObject", "MyUnityMethod", "Hello from React!").

内容的提问来源于stack exchange,提问作者Nicolás Riccardi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:02:19