1.将unity给的包放在public路径下。
2.在iframe中引入。
<iframe ref="Unity" id="unity" width="100%" height="100%" frameborder="0"
allowfullscreen="true" scrolling="yes" src="/你放unity资源的路径index.html"
/>
3.在vue项目中监听unity中的事件。关闭页面的时候需要销毁。
// 在unity的index.html的页面中
// 在初始化GlobalUnityInstance的时候定义事件
var GlobalUnityInstance = null
createUnityInstance(document.querySelector('#unity-canvas'), {
dataUrl: 'xx',
frameworkUrl: '.xx',
codeUrl: './xx',
streamingAssetsUrl: 'xx',
companyName: 'xx',
productName: 'xx',
productVersion: 'xx'
}).then((unityInstance) => {
GlobalUnityInstance = unityInstance
window.top.dispatchEvent(new CustomEvent('UNClick', params))
}).catch((message) => {
})
// 在vue的项目页面中
mounted() {
window.addEventListener('UNClick', this.unityWatch)
},
destroyed() {
window.removeEventListener('UNClick', this.unityWatch)
},
// 事件
// unity发送事件执行
unityWatch(obj) {
// 接收到事件后的执行逻辑
},
4.vue页面向unity发送参数信息。
this.$refs.Unity.contentWindow.postMessage(params)
5.在unity中的index.html文件中接收页面传来的参数。
window.addEventListener('message', (ev) => {
console.log('收到消息', ev)
})
6.调用unity内部的事件。
unitySendMessage() {
/** 参数:参考其他大佬写的
* 1. unity定义的对象名字(直接问工程师名字是什么,或者看indie.html中,
GlobalUnityInstance.SendMessage('第一个名字')
* 2. 调用unity的方法名字
* 3. unity接收的参数
*/
this.$refs.iframe.contentWindow.unityInstance.SendMessage('名字', 'UnityActive', 参数)
},