栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

Unity WebGL C#调用JS脚本

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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:学习笔记

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/900760.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号