Unity WebGL UnityScript与JavaScript通信


在这里插入图片描述

原理

UnityScript(WebGL)与JavaScript(Web)交互

Web
WebGL
发送消息Send
接收消息onReceivedMsg
发送消息SendMsg2WebGL
接收消息AddRecieveWebGLMsgListener
index.html
WebGLCommunicator.js
ZYF_WebCommunicator.cs
WebCommunicator.jslib
...

工具导入

  1. 下载WebCommunicator工具包👈,导入到Unity中。(另外还需要Odin插件🤫
    在这里插入图片描述

  2. 双击导入WebGLCommunicator(JsTool)
    在这里插入图片描述
    再把WebGLCommunicator文件夹拖到自己的模板中
    在这里插入图片描述

UnityScript(WebGL) ⇐⇒ JavaScript(Web)

一.UnityScript(WebGL)

1. 在场景中添加脚本并初始化

在这里插入图片描述

2. 发送消息给Web

在这里插入图片描述

3.接收Web消息

在这里插入图片描述

二.JavaScript(Web)

1.添加消息监听

打开模板中的index.html,导入工具并监听WebGL消息
在这里插入图片描述

<!-- webGL与web互相通信 -->
<script type="text/javascript" src="WebGLCommunicator/WebGLCommunicator.js"></script>
<!-- 监听WebGL消息 -->
<script type="text/javascript">
   AddRecieveWebGLMsgListener(function(msg) {
      console.log('处理 WebGL消息。。。:', msg);
   });
</script>

2.发送消息给WebGL

在这里插入图片描述

<div style="position:absolute;width: 200px; height: 100px;z-index:2;">
   <button type="button" onclick="SendMsg2WebGL('Hi i am web')">从Web发送消息给WebGL</button>
</div>

错误处理

gameInstance is not defined

在这里插入图片描述
1.先确定打包后index.html中Unity示例名称
在这里插入图片描述
2. 修改Unity编辑器中的WebGLCommunicator.js
在这里插入图片描述
在这里插入图片描述
改成对应的unityInstance,重新打包,清除浏览器缓存运行

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牙膏上的小苏打2333

哟,哟,切克闹,煎饼果子来一套

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值