Unity WebGL C#调用JS脚本

官网文档

目录

一、Unity调用JS脚本

二、JS调用Unity脚本


一、Unity调用JS脚本

1.首先在Unity/Assets/Plugins目录下存放你需要调用的JS脚本

2.在Plugins目录下新建文本文档,后缀改为jslib。

纂写JS脚本内容:

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]);
  },

});

3.在Scripts目录下新建C# 脚本

 [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((int)texture.GetNativeTexturePtr());
    }

4.打包测试或者直接Buid And Run 进行测试

二、JS调用Unity脚本

1.首先在场景中新建一个(名字唯一的)物体,并且挂载你需要调用的脚本。以下为我的场景和对应脚本

 public void JSCallUnity1()
    {
        Debug.Log("JSCALLUnity Without Value");
    
    }
    public void JSCallUnity2(string value)
    {
        Debug.Log("JSCALLUnity Without" +value);

    }

 2.打包web文件,打开index.html文件进行编辑,在70多行左右,全屏按钮的事件上加上我们的访问代码

unityInstance.SendMessage('场景中挂载脚本的物体名','方法名')
unityInstance.SendMessage('场景中挂载脚本的物体名','方法名','方法对应参数')

 3.然后浏览器打开Index.html,点击全屏显示按钮可以看到网页控制台输出信息。

 

PS:学习笔记

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>