一、前端发数据到unity程序
写js->unity
该过程不需要添加额外的jslib文件,可在脚本中直接调用sendMessage。
只需要把打包好的webGL程序包放到合适的地方(http服务可调用),修改webgl包里有index.html文件
调用方式如下
<buttontype="button"onclick="callUnity('这是发送给unity的一封信')">send</button>
...
<script>
varmyInstance=null;
//后续进行实例化
//js调用C#方法
functioncallUnity(msg){
myInstance.SendMessage("sendPanel","recvmsg",msg);
}
varscript=document.createElement("script");
script.src=loaderUrl;
script.onload= () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width=100*progress+"%";
}).then((unityInstance) => {
myInstance=unityInstance;
loadingBar.style.display="none";
fullscreenButton.onclick= () => {
unityInstance.SetFullscreen(1);
};
}).catch((message) => {
alert(message);
});
};
</script>
上述SendMessage方法的三个参数依次是:
unity程序中挂载c#脚本的物体的name
c#脚本实现的接收前段传参的中的函数
实际传的参数
测试效果,点击页面中send按键,unity文本框中显示收到信息。

二、unity程序发送数据到前端
unity->js
1.新建×××.jslib文件
在unity项目Assets/Plugins下新增test.jslib文件
sendInto(LibraryManager.library, {
SendMsgToFrontend: function (msg) {
console.log("SendMsgToFrontend msg=="+msg)
},
})
2.unity声明调用函数并调用
在挂载接收消息的c#脚本中声明js函数
并在预期的地方调用该函数
[DllImport("__Internal")]
publicstaticexternstringSendMsgToFrontend(stringmsg);
publicasyncvoidButtonClick()
{
SendMsgToFrontend("send: message to js.");
}
3.js脚本中接收数据
js脚本中写监听方法
varmyInstance=null;
//C#调用js方法
functionSendMsgToFrontend(msg){
windows.alert(msg);
}
通过前端的console方式查看收到的结果
