Interaction between WebGL and web pages published by Unity2021

Keywords: Unity webgl

(1) First, let's talk about how Unity calls page methods.

First, create a Plugins folder in the Asset directory of the project, and then create a. txt file in the folder. The name doesn't matter. After creation, change the extension to. jslib. The file shall contain the following contents:

mergeInto(LibraryManager.library, {

  Hello: function () {
    window.alert("Hello, world!");
  },

  HelloString: function (str) {
    window.alert(Pointer_stringify(str));
  },

  PrintFloatArray: function (array, size) {
    for(var i = 0; i < size; i++)
    console.log(HEAPF32[(array >> 2) + i]);
  },

  AddNumbers: function (x, y) {
    return x + y;
  },

  StringReturnValueFunction: function () {
    var returnStr = "bla";
    var bufferSize = lengthBytesUTF8(returnStr) + 1;
    var buffer = _malloc(bufferSize);
    stringToUTF8(returnStr, buffer, bufferSize);
    return buffer;
  },

  BindWebGLTexture: function (texture) {
    GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]);
  },

});

Among them, only the second parameter of mergeInto can be modified. The second parameter is an object (that's right. I'm not familiar with JavaScript. I hope I'm right.) this object contains multiple methods. These methods (such as Hello (), BingdeWebGLTexture ()) can be introduced in Unity programming. The methods called within these methods (such as wiindow.alert(), GLctx.bindTexture(), etc.) can be called in future pages.

Specific methods introduced in Unity programming take C# as an example:

First, you need to introduce a namespace:

using System.Runtime.InteropServices;

Secondly, you need to write specific import Codes:
[DllImport("__Internal")] private static extern void Hello();

Refer to the following code introduction and use examples

using UnityEngine;
using System.Runtime.InteropServices;

public class NewBehaviourScript : MonoBehaviour {

    [DllImport("__Internal")]
    private static extern void Hello();

    [DllImport("__Internal")]
    private static extern void HelloString(string str);

    [DllImport("__Internal")]
    private static extern void PrintFloatArray(float[] array, int size);

    [DllImport("__Internal")]
    private static extern int AddNumbers(int x, int y);

    [DllImport("__Internal")]
    private static extern string StringReturnValueFunction();

    [DllImport("__Internal")]
    private static extern void BindWebGLTexture(int texture);

    void Start() {
        Hello();
        
        HelloString("This is a string.");
        
        float[] myArray = new float[10];
        PrintFloatArray(myArray, myArray.Length);
        
        int result = AddNumbers(5, 7);
        Debug.Log(result);
        
        Debug.Log(StringReturnValueFunction());
        
        var texture = new Texture2D(0, 0, TextureFormat.ARGB32, false);
        BindWebGLTexture(texture.GetNativeTextureID());
    }
}

(2) Secondly, let's talk about how page methods call methods in Unity.

Simply put, just send a message using unityInstance. The specific method is defined as follows:

unityInstance.SendMessage(objectName, methodName, value);

The parameter objectName is the name of the object in the Unity scene list. Here, pay attention to ensure that there is only one object with this name in the scene, and do not have duplicate names, otherwise it will be messy. methodName is the name of the method that sends the message, and value is the parameter of the method. This parameter can be none, and some can be integers or strings.

Refer to the following for specific usage:

unityInstance.SendMessage('MyGameObject', 'MyFunction'); unityInstance.SendMessage('MyGameObject', 'MyFunction', 5); unityInstance.SendMessage('MyGameObject', 'MyFunction', 'MyString');

However, this unityInstance is an internal object (I don't know how to say this is more accurate, let's say it first for the time being). If you want to reference this object externally, please refer to the following page code:

var myGameInstance = null;
      createUnityInstance(canvas, config).then((unityInstance) => {myGameInstance = unityInstance;});
	  
var SendCmd = function(funName){
		myGameInstance.SendMessage("ZongCai", funName);
}

In this way, you can use myGameInstance to obtain the reference of unityInstance, and you can use myGameInstance to send messages.

Official reference:

WebGL: interacting with browser scripts - Unity manual

Posted by Stargate on Fri, 29 Oct 2021 00:24:21 -0700