Skip to content

Event handler for Unity Events is global #109

@stefanb2

Description

@stefanb2

Describe the bug
In our application we have two Unity WebGL components, out of which max one is visible at a time. Both components share a code base, e.g. they both send the UnityEventDispatch Unity Event to pass events to the React side. After calling

this.unityContent.on('UnityEventDispatch', this.unityEventDispatch)

in the instance constructor only one of the event handlers is ever called.

To Reproduce

ReactUnityWebGL.jslib:

mergeInto(LibraryManager.library, {
  ...
  UnityEventDispatch: function(json) {
    ReactUnityWebGL.UnityEventDispatch(Pointer_stringify(json));
  },
  ...
});

WebGLBridge.cs:

...
using UnityEngine;
using System.Runtime.InteropServices;
...

public static class WebGLBridge
{
  // These are defined as JS plugins at Assets/Plugin/ReactUnityWebGL.jslib
  ...
  [DllImport("__Internal")]
  private static extern void UnityEventDispatch(string json);
  ...
  public static void SendExternalEvent(string eventName, ...)
  {
    var data = ... // create some object that .ToString() converts to JSON string
    ...
    string json = data.ToString();
    UnityEventDispatch(json);
  }
}

UnityWrapper.js (React side)

export default class UnityWrapper extends Component {
  ...
  constructor(props) {
    ...
    this.unityContent = new UnityContent(this.configPath, this.unityLoader);
    ...
    this.unityContent.on('UnityEventDispatch', this.unityEventDispatch);
    ...
  }
  ...
  unityEventDispatch = data => {
    // parse JSON, forward event to callback and so on...
  };
  ...
}

When Unity Component 1 calls WebGLBridge.SendExternalEvent() then the event handler on the UnityContent instance for the other component is called. I didn't verify this, but I think that this depends on the order of instance creation, i.e. the last created UnityContent will override the event handler for the same event of a previous UnityContent instance.

Expected behavior
When Unity Component 1 calls WebGLBridge.SendExternalEvent() then the event handler for its UnityContent instance will be called.

Desktop

  • OS: Linux
  • Browser: Chromium
  • Version: 84
  • JSON from component build output: unityVersion: "2019.3.5f1"
  • package.json: "react-unity-webgl": "^7.1.10",

Metadata

Metadata

Assignees

No one assigned

    Labels

    staleInactive for too long

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions