jeffreylanters / react-unity-webgl

React Unity WebGL provides a modern solution for embedding Unity WebGL builds in your React Application while providing advanced APIs for two way communication and interaction between Unity and React.
https://react-unity-webgl.dev
Apache License 2.0
1.75k stars 162 forks source link

dispatchReactUnityEvent is not a function #439

Closed ReginaldBull closed 2 years ago

ReginaldBull commented 2 years ago

Please avoid duplicates

Language and Compiler

TypeScript's built-in Compiler

What environment are you using?

Other

When does your problem occur?

When the Unity App is running

What does your problem relate to?

I don't know

React-Unity-WebGL Version

9.0.4

React Version

17.0.2

Unity Version

2020.3.37f1

What happened?

Hello,

Followed the instructions in the documentation. In Unity I created under Plugins/WebGL a file "React.jslib" with following content:

mergeInto(LibraryManager.library, {
    UnityContextInitialized: function (message) {
        try{
            console.log("Unity: " + UTF8ToString(message));
            window.dispatchReactUnityEvent("UnityContextInitialized", UTF8ToString(message));
        } catch(e) {
            console.error(e);
        }
    },
});

Inside of Unity

public sealed class ConfigurationApi : MonoBehaviour, IConfigurationApi
    {
        [DllImport("__Internal")]
        private static extern void UnityContextInitialized(string message);

        public void Initialize(string json)
        {   
            InitializeAsync(json)
                .GetAwaiter()
                .GetResult();
#if UNITY_WEBGL == true && UNITY_EDITOR == false
            UnityContextInitialized("Initialized");
#endif
        }
}

The Initialize method is called by the React-Frontend and works.

Now I want to give a message back after the initialization happened. Therefore, I added the UnityContextInitialized("Initialized") call.

While the project is run and opened, the following message shows up in the console output:

TypeError: window.dispatchReactUnityEvent is not a function.

I see the log message from this console.log: console.log("Unity: " + UTF8ToString(message));

Any ideas?

Reproducible test case

No response

Would you be interested in contributing a fix?