在参考网上众多资料后,终于将Vue与Unity Webgl双向通信的功能完成。在此过程中遇到了很多问题,故记录下整体流程。
方案实现:
1.unity端实现一个jslib文件预定义函数作为桥接。
2.c#使用DllImport引入和调用预定义的函数。
3.web端使用js定义被调用函数。
1.Unity Webgl程序嵌入vue
2.Unity -> vue通信
3.vue -> Unity通信
1.Unity Webgl程序嵌入vue
1)在Unity打包生成webgl项目后,将webgl文件夹内容复制到vue项目目录下的static文件夹中
添加Web.Config文件,内容如下:
2)在vue项目中以iframe的方式调用
2.Unity -> vue通信
1)在unity创建好项目后,在Assets目录下新建Plugins文件夹,创建一个jslib文件,可以用txt创建文件,文件名加后缀名为“xxx.jslib”,切记后缀名更改为jslib
jslib当作中间者,unity与它通信,前端也与它通信,在此基础上三者之间进行了通信对接
2)在刚刚创建的jslib文件里,添加以下代码:
mergeInto(LibraryManager.library,{
//Unity内自定义调用方法名 PostScore(string sceneName)
PostScore: function (sceneName) {
strs = Pointer_stringify(sceneName); //字符串需用Pointer_stringify转换
GetScore(strs); //前端自定义方法名GetScore(strs)
},
});
3)在unity中,新建一个脚本,添加命名空间using System.Runtime.InteropServices; 并添加以下C#代码:
[DllImport("__Internal")]
private static extern void PostScore(string currentScene); //当前场景
在unity中调用PostScore()方法,即调用jslib里的PostScore()方法
4)打包时在Player Settings->Player->Publishing Settings中将压缩格式禁用,平台选择Webgl
5)在unity打包程序后,在index.html中添加GetScore()方法
以上是unity基础的向前端通信方式。
此时我们在网页嵌入的Unity页面中点击交互按钮时即可触发PostScore(str)方法,将数据从Unity页面传输到前端html中。
3.vue -> Unity通信
官方文档
前端页面向unity页面传值需用到unityInstance.SendMessage()函数,调用格式如下:
SendMessage(unityObject,unityMethodName,value)
unityObject——unity脚本挂载对象名
unityMethodName——unity脚本内调用方法名(需为public方法)
value——前端需要传出的值
1) 在Unity2022.3版本打包生成的webgl中不能直接找到unityInstance对象,需要在index.html页面作如下处理,自定义一个myGameInstance对象用于获取unityInstance
var myGameInstance = null;
createUnityInstance(document.querySelector("#unity-canvas"), {
...//省略代码
}).then((unityInstance) => {
myGameInstance = unityInstance;
});
2)之后就能愉快的在vue页面调用该方法了~
const refreshAllItem = ()=>{
console.log('当前unity对象', unityvue.value)
unityvue.value.contentWindow.myGameInstance.SendMessage('WeatherControl', 'TransToAfternoon', "")
}
参考文档
在此感谢以下作者的参考资料~
网页传递参数到Unity WebGL ,WebGL传递参数到网页_webgl unityinstance_先生沉默先的博客-CSDN博客
WebGL给Unity传递参数问题1: Cannot read properties of undefined (reading ‘SendMessage‘)_先生沉默先的博客-CSDN博客
Unity(WebGL)与JS通讯2022最新姿势 - 知乎
web通信 - web 调用unity方法_哔哩哔哩_bilibili
推荐阅读
发表评论