Unity WebGL交互通信

Unity 调用 H5

本文使用的 unity 版本为:2021.3.3

1.在unity中通过c#的特性DllImport导出外部实现函数

csharp 复制代码
    [DllImport("__Internal")]
    private static extern void callJsString(string param);
    [DllImport("__Internal")]
    private static extern void callJsInt(int param);
    [DllImport("__Internal")]
    private static extern void callJsFloat(float param);
    [DllImport("__Internal")]
    private static extern void callJsBoolean(bool param);

2.在unity的Plugins文件夹(没有则创建一个)里面创建一个后缀为.jslib的文件

3.在xxx.jslib文件中实现函数,如下

javascript 复制代码
mergeInto(LibraryManager.library, {

  callJsString: function (param) {
     console.log(Pointer_stringify(param));
  },

  callJsInt: function (param) {
       console.log(param);
  },
  
   callJsFloat: function (param) {
       console.log(param);
  },
   callJsBoolean: function (param) {
       console.log(param);
  },
});

注意: 使用传参字符串的时候,使用Pointer_stringify转下字符串,否则可能会报错或者乱码

4.如果想要调用.js里面的接口或者.html里面的方法,可以通过往window里面注册函数进行调用的方式

例如:在index.html里面注册函数 window.httpPost = httpPost;

javascript 复制代码
<script>
   function httpPost(url, params) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                let data = xhr.response;
                console.log("Status: " + xhr.status + " " + xhr.statusText + "  data: " +         data);
                success(data);
            }
            else if (xhr.status >= 400) {
                console.log("Status: " + xhr.status + " " + xhr.statusText);
                fail(xhr.status, xhr.statusText)
            }
        }
        console.log("Status: Send Post Request to " + url);
        xhr.open("POST", url, true);
        //xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.timeout = 10000;

        xhr.send(params);
    }

   window.httpPost = httpPost;
</script>

5.可以在xxx.jslib文件中调用index.html里面的httpPost函数,当时也可以直接把函数实现直接放在xxx.jslib文件中

javascript 复制代码
mergeInto(LibraryManager.library, {

  callJsString: function (url,params) {
     window.httpPost(Pointer_stringify(url),Pointer_stringify(params)); 
  },
});

6.上面的方式可以让我们在案例httpPost调用其他位置的.js代码或者其他位置的插件

H5调用 Unity

1.这里的方式主要是在index.html文件中在创建unityInstance的时候通过缓存unityInstance并向unityInstance发送消息的方式实现

2.在index.html中创建unityInstance的时候缓存unityInstance

这里通过:window.unityInstance = unityInstance; 缓存了unityInstance实例

javascript 复制代码
         var script = document.createElement("script");
            script.src = loaderUrl;
            script.onload = () => {
              createUnityInstance(canvas, config, (progress) => {
                progressBarFull.style.width = 100 * progress + "%";
              }).then((unityInstance) => {
                loadingBar.style.display = "none";
                fullscreenButton.onclick = () => {
                  unityInstance.SetFullscreen(1);
                };
                window.unityInstance = unityInstance;
              }).catch((message) => {
                alert(message);
              });
            };

3.向unity发送消息

gameobjectName:接收消息的gameobject名

funcName:方法名

param:参数,字符串,可以传json

javascript 复制代码
 function sendUnityMessage(gameobjectName,funcName,param) 
 {
      if(window.unityInstance)
      {
         window.unityInstance.SendMessage(gameobjectName,funcName,param);
      }
 }
相关推荐
Panzer_Jack1 天前
如何用 WebGL 去实现一个选取色彩背景图片透明化小工具 - Pick Alpha
前端·webgl
烛阴2 天前
Three.js 零基础入门:手把手打造交互式 3D 几何体展示系统
javascript·webgl·three.js
叶智辽3 天前
【ThreeJS调试技巧】那些让 Bug 无所遁形的“脏套路”
webgl·three.js
叶智辽4 天前
【ThreeJS急诊室】一个生产事故:我把客户的工厂渲染“透明”了
webgl·three.js
weixin_424294674 天前
Unity 调用Steamworks API 的 SteamUserStats.RequestCurrentStats()报错
unity·游戏引擎·steamwork
HoFunGames4 天前
Unity小地图,Easy Minimap System MT-GPS插件
unity·游戏引擎
微学AI4 天前
从云端到指尖:重构 AI 终端生态与实体交互新范式
人工智能·重构·交互
The️4 天前
Linux驱动开发之Read_Write函数
linux·运维·服务器·驱动开发·ubuntu·交互
AI能见度4 天前
硬核:如何用大疆 SRT 数据实现高精度 AR 视频投射?
ar·无人机·webgl
wy3258643644 天前
Unity 新输入系统InputSystem(基本操作)
unity·c#·游戏引擎