Referenceerror: MyGameInstance is not defined Unity 2021.2

My WebGL build using Unity 2021.2
I’m trying to get my jslib plugin to talk back to Unity but can’t even get it to return to Unity no matter what I try.

According to the documentation Unity - Manual: Interaction with browser scripting (unity3d.com)
I’ve edited the build index.html to include the myGameObject (myUnityInstance)

I’ve setup a button click to trigger the js code and then throws the error

ReferenceError: MyUnityInstance is not defined as _GetString

the js code

mergeInto(
  LibraryManager.library,
  {
    GetString: function(){

      var str = "This is a string";
      var buffersize = lengthBytesUTF8(str) +1;
      var buffer = _malloc(buffersize);
      stringToUTF8(str, buffer, buffersize);     
      MyUnityInstance.SendMessage('JSUrl', 'JSReturnString', 'buffer');
      return buffer;
     
    }
  }
   
);

the C# function

    public void JSReturnString(string returnStr)
    {
         print("Returned String: " + returnStr);

    }

index.html

      var myUnityInstance = null;
      script.src = loaderUrl;
      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 100 * progress + "%";
        }).then((unityInstance) => {
            myUnityInstance = unityInstance;
          loadingBar.style.display = "none";
          fullscreenButton.onclick = () => {
            unityInstance.SetFullscreen(1);
          };
        }).catch((message) => {
          alert(message);
        });
      };
1 Like

You create myUnityInstance but you use MyUnityInstance

It throws the same error unfortunately. myUnityInstance is undefined

Can you try to replace myUnityInstance = unityInstance; by window.MyUnityInstance = unityInstance;

You use “MyUnityInstance.SendMessage” in your JS, so it must be MyUnityInstance with an uppercase not myUnityInstance with a lowercase

adding “window.” will give you a global scope.

1 Like

So I managed to get it working in the end.

I didn’t need MyUnityInstance, instead just used

SendMessage('JSUrl', 'JSReturnString', 'buffer');

I had tried that bit of code before but didn’t work but now it does. It is passing “buffer” now.
I believe when I tried before I was trying to get to print to a UI label and that was not setup right hence the confusion.

It was the classic moment, my code doesn’t work and don’t know why. My code works and don’t know why.

That said I was not aware that window give me global scope so thank you for that.

3 Likes

I spent 3 days trying to get async to return. Thank so much for the clarification. Surprised that this is still an issue. This worked when my script was attach to gameObject.
SendMessage('ObjectName', 'Function In Script(not ScriptName)', 'Message');

1 Like

Thank you for this!
Worked for me too to just call SendMessage() directly.