在 React 项目中导入 Unity 文件

Import Unity file in React project

我在 React 项目中加载 Unity 文件时遇到问题。我想如果我在 index.html 中添加文件,我将能够在项目的任何地方使用 UnityLoader ,如下所示:

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Game</title>
  </head>
  <body>
    <div id="app">
    </div>
    <script src="UnityLoader.js"></script>
  </body>
</html>

Unity.js

class Unity extends Component {

    render() {
        return (
            <div id="unity">
                {UnityLoader.instantiate('unity', 'unity/index.html')}
            </div>
        );
    }
}

但是,我收到一条错误消息,指出 UnityLoader 未定义。

我需要使用某种

import { UnityLoader } from 'UnityLoader' 

Unity.js?问题是 UnityLoader 是一个外部 JS 文件,不会导出任何内容。

为什么不通过 npm 安装 React-Unity 然后将其导入到您的组件中?

import React, { Component } from 'react';
import { Unity } from 'react-unity-webgl';


export class App extends Component {
  render() {
    return (<div className="app">
      <Unity src="Build/myGame.json" />
        </div>)
    }
}

不要忘记添加脚本标签以加载 UnityLoader.js 文件,该文件由 Unity 在您的基础 html 文件中导出。

<script src="build_unity/Build/UnityLoader.js"></script> 
<script src="compiled/bundle.js"></script>