一、前言
在一個新的項目中,要在頁面中嵌入三維部門用 Unity3D 做的場景。在摸索中使用了一些方法。下面是對這些總結。
二、Iframe 嵌入
這種做法是,先寫一個簡單的 HTML ,把 Unity3D 包含進來。再在項目中用 Iframe 嵌入。
HTML 代碼:
<body> <div id="gameContainer"></div> <div id="loader"> <img class="logo" src="logo.png"> <div class="spinner"></div> <div class="progress"><div class="full"></div></div> </div> </body> <script src="Build/UnityLoader.js"></script> <script> var gameInstance = UnityLoader.instantiate("gameContainer", "Build/8.json", {onProgress: UnityProgress}); function UnityProgress(gameInstance, progress) { if (!gameInstance.Module) { return; } const loader = document.querySelector("#loader"); if (!gameInstance.progress) { const progress = document.querySelector("#loader .progress"); progress.style.display = "block"; gameInstance.progress = progress.querySelector(".full"); loader.querySelector(".spinner").style.display = "none"; } gameInstance.progress.style.transform = `scaleX(${progress})`; if (progress === 1 && !gameInstance.removeTimeout) { //gameInstance.removeTimeout = setTimeout(function() { loader.style.display = "none"; //}, 2000); } } function UnitySceneIsReadyJSNative() { //alert("UnitySceneIsReady JS Native Here "); gameInstance.SendMessage("JSManager", "SendData", "Come From JS Message"); } </script>
上面代碼中使用到的文件是:
UnityLoader :Unity 加載用的
8.json : Unity3D 文件
把這個文件用 Nginx 代理下,在項目中就可以直接使用了:
<iframe id="unity-infame" :src="unityUrl" frameborder="0" width="100%" height="100%" scrolling="no" />
unityUrl 是代理后的地址
這樣對於只是看一看沒有問題,但是當需要和 Unity3D 進行通信就不行了。
三、第三方組件
遇到上面的問題后,想應該會有開源的組件可以用的。
於是搜索了是否有在 Vue 中使用的 Unity3D 的包。
搜索到了幾個:unity-packman、vue-unity-webgl(這些都可以在 npm 網站搜索到),對比着兩個后,發現 vue-unity-webgl 更適合。
安裝完成,按照示例寫了如下代碼:
<template> <div class="flood-plan-page"> <unity ref="unityPlan" src="static/Build/8.json" class="unity-box" unity-loader="static/Build/UnityLoader.js" /> </div> </template> <script> import Unity from 'vue-unity-webgl' export default { components: { Unity },
}
</script>
對於樣式這一塊來說,官方說的的是直接 .unity 就是對應的樣式包含塊,但是不生效。在看了渲染后的代碼后,使用如下樣式
.webgl-content { position: absolute; width: 965px; height: calc(100% - 212px); left: 368px; top: 10px; #unity-container { height: 100%; width: 100%; } .footer { position: absolute; left: 5px; bottom: 5px; } }
.webgl-content 是包含塊。
使用后手動銷毀 Element:
使用該組件,在頻繁切換頁面,顯示不顯示的時候瀏覽器占用內存一直增加。
在 Vue 中 v-if 是直接刪除 Element,所以在銷毀組件前刪除 Element
<unity v-if="isShowUnity" ref="unityPlan" :hide-footer="true" src="" unity-loader="" /> beforeDestroy() { this.isShowUnity = false this.distroySocket() }
四、和 Unity 通信
通信主要有:主動和被動
主動通信:直接調取 Unity 里面的方法等,具體操作:
// 這個是在 Vue 里面,使用上面的 vue-unity-webgl // unityPlan 是組件暴露的實例 // 參數前面兩個是 unity 中的類、方法,最后一個是參數 this.$refs.unityPlan.message('JSManager', 'SendData', '環丁水系')
被動通信:unity 調用本地代碼,具體操作:
// 需要把要被調用的方法掛載在 window 下面 // 放在 mounted 鈎子里面 mounted() { // 播放監控(和 unity 交互) window['UnityCallMonitorJSNative'] = (code) => { this.monitorCode = code } }
問題:
在簡單測了幾遍后,發現再全屏返回時控制台出現很多報錯信息。后面打算再做調整