Unity 打包 WegGL后与浏览器的通信,解决JS无法使用SendMessage

  • unity 调用浏览器 js

直接看 官方文档 调用没什么问题,传值都可以

  • js 调用 unity 方法

首先在 webgl 打包好的 index.html中写一个按钮,用来触发我们的js

Script部分写在打包生成的js段落中就可以了 

 1       var script = document.createElement("script");
 2       var gameInstance = null;
 3       script.src = loaderUrl;
 4       script.onload = () => {
 5         createUnityInstance(canvas, config, (progress) => {
 6           progressBarFull.style.width = 100 * progress + "%";
 7         }).then((unityInstance) => {
 8           gameInstance = unityInstance;
 9           loadingBar.style.display = "none";
10           fullscreenButton.onclick = () => {
11             unityInstance.SetFullscreen(1);
12           };
13         }).catch((message) => {
14           alert(message);
15         });
16       };
17       document.body.appendChild(script);
18 var button = document.querySelector("#on-number"); 19 button.onclick = function() { 20 //调用函数 SendMessage 21 gameInstance.SendMessage('Player', 'OnNumber', parseInt(Math.random()*(99)+1,10)); 22 }

button.onclick 用来触发 SendMessage 方法,调用 Unity 中公开暴露的方法 OnNumber

注意点:需要 定义一个 gameInstance 并且暴露出来,在 createUnityInstance 后接收到 unityInstance 并储存,代码第2、第8行。

很多教程/博客并不会说明白这一点,而直接上示例unityInstance.SendMessage发送消息。

unityInstance 并不是可以直接调用的,需要我们获取。

否则就会出现报错 unityInstance/gameInstance is undefined

posted @ 2022-02-18 11:23  Yunssss  阅读(1071)  评论(1编辑  收藏  举报