一、添加unity工程
unity工程師會提供一個前端可使用的包,將其放在vue項目的public
下,我這里以unity
文件夾命名
二、在項目中創(chuàng)建iframe標簽并引入index.html文件
<iframe id="iframe" ref="iframe" src="/unity/index.html" width="100%" height="100%" frameborder="0" scrolling="auto" />
三、修改public > unity > index.html文件,制定發(fā)送到web端事件
文章來源:http://www.zghlxwxcb.cn/news/detail-789912.html
// unity按鈕點擊發(fā)送事件
function UIClick(btnname){
window.top.dispatchEvent(new CustomEvent('UIClick', { detail: { name: btnname } }))
}
四、在引入unity的vue文件中監(jiān)聽接收unity發(fā)送事件, 因為我使用了頁面緩存所以在activated()生命周期中監(jiān)聽,根據(jù)業(yè)務需要也可以在mounted()生命周期中監(jiān)聽
activated() {
window.addEventListener('UIClick', this.unityWatch)
},
// 或者
mounted() {
window.addEventListener('UIClick', this.unityWatch)
},
methods: {
// unity發(fā)送事件執(zhí)行
unityWatch(obj) {
console.log(obj.detail); // 這里寫需要的后續(xù)js邏輯
},
}
五、vue發(fā)送事件給unity
unitySendMessage() {
/** 參數(shù):
* 1. unity定義的對象(每個unity工程師喜歡的名字不一樣)
* 2. 調(diào)用unity的方法名字
* 3. unity接收的參數(shù)
*/
this.$refs.iframe.contentWindow.unityInstance.SendMessage('WebInvoker', 'Unity_InsertNaviPoint', '這是參數(shù)')
},
六、銷毀監(jiān)聽
deactivated() {
window.removeEventListener('UIClick', this.unityWatch)
}
// 或者
destroyed() {
window.removeEventListener('UIClick', this.unityWatch)
}
七、完整代碼
<template>
<div>
<iframe id="iframe" ref="iframe" src="/unity/index.html" width="100%" height="680px" frameborder="0" scrolling="auto" />
</div>
</template>
<script>
export default{
activated() {
// 監(jiān)聽unity發(fā)送事件
window.addEventListener('UIClick', this.unityWatch)
},
methods: {
// 調(diào)用unity內(nèi)部事件
unitySendMessage() {
/** 參數(shù):
* 1. unity定義的對象(每個unity工程師喜歡的名字不一樣)
* 2. 調(diào)用unity的方法名字
* 3. unity接收的參數(shù)
*/
this.$refs.iframe.contentWindow.unityInstance.SendMessage('WebInvoker', 'Unity_InsertNaviPoint', this.nodeList.length)
},
// unity發(fā)送事件執(zhí)行
unityWatch(obj) {
console.log(obj.detail); // 這里寫需要的后續(xù)js邏輯
},
},
deactivated() {
window.removeEventListener('UIClick', this.unityWatch)
}
}
</script>
展示效果
文章來源地址http://www.zghlxwxcb.cn/news/detail-789912.html
到了這里,關(guān)于vue項目接入unity3D模塊并進行數(shù)據(jù)通信的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!