Reactjs combined with unity webgl causes errors

1.9k views Asked by At

I'm a bit new to unity and this is my first time creating a thread here so maybe i'm asking a dumb question.

I'm creating a website using react and a part of this website has a game which uses unity. The problem i'm having is that i'm using react for this webapplication which causes errors when unity gets reloaded by react.

normally unity gets loaded only once by the unityloader.js file. However the way i have my react application setup every time a certain react compent gets loaded this piece of code causes unity to load

componentWillMount() {
        const script = document.createElement("script");
        script.src = "Release/UnityLoader.js";
        script.async = true;
        document.body.appendChild(script);
    }

The first time i do this loading everything works fine but when i revisit the page that contains this unitywebgl compenent, unity crashes and i get the following error.

Uncaught TypeError: Cannot read property 'apply' of undefined
    at Object.dynCall (blob:http://localhost:8000/11f3d503-5e8a-473e-851f-2373f9cb5de6:1)
    at Object.handlerFunc (blob:http://localhost:8000/11f3d503-5e8a-473e-851f-2373f9cb5de6:1)
    at jsEventHandler (blob:http://localhost:8000/11f3d503-5e8a-473e-851f-2373f9cb5de6:1)

Maybe i'm doing something wrong and i'm using some strange way to initialize unity. However it's important for this webapplication to often initialize and reload unity. Is there maybe some function in unityloader.js to give it a canvas and manually ask it to reload or am i heading in the wrong direction?

1

There are 1 answers

0
Jeffrey ジェフリー On

I made an NPM module for adding Unity content in your ReactJS application. A basic implementation could look something like;

import React from 'react';
import Unity from 'react-unity-webgl';

export class App extends React.Component {
    render () {
        return <Unity 
            src='Build/myGame.json' 
            loader='Build/UnityLoader.js' />
    }
}