vue使用iframe内嵌unity模型,并且向模型传递信息,接受信息

1 静态模型地址

放在跟src同级的static里边,testHtml就是需要嵌的网页

2 TestHtml文件内容

html 复制代码
<body>
    <div id="unity-container">
        <canvas id="unity-canvas"></canvas>
    </div>

    <script src="Build/KEIPER_12_18.loader.js"></script>
    <script>
        let unityInstance = null;

        createUnityInstance(document.querySelector("#unity-canvas"), {
            dataUrl: "Build/KEIPER_12_18.data",
            frameworkUrl: "Build/KEIPER_12_18.framework.js",
            codeUrl: "Build/KEIPER_12_18.wasm",
            streamingAssetsUrl: "StreamingAssets",
            companyName: "DefaultCompany",
            productName: "KEIPER_2025_1211",
            productVersion: "1.0",
        }).then(instance => {
            unityInstance = instance;
            console.log("Unity loaded");

            window.addEventListener('message', (event) => {
                console.log("模型收到来自父窗口的消息:", event.data)
                if (event.data.type == 'call-callUnity') {
                    callUnity(JSON.stringify(event.data.data));

                }
            })

            
        });


        function callUnity(msg) {
            if (!unityInstance) {
                console.warn("Unity not ready");
                return;
            }

            //进行切片发送
            const jsonStr = typeof msg === "string" ? msg: JSON.stringify(msg);          
            const size = 1024;
            const total = Math.ceil(jsonStr.length/size);

            for(let i=0;i<total;i++){
                const chunk = jsonStr.substr(i * size, size);
                strNew =  i + "/" + total + "|" + chunk;
                unityInstance.SendMessage(
                    "WebGLSendAndReceiver",
                    "OnReceiveMessage",
                    i + "/" + total + "|" + chunk
                );

               //alert(strNew);

            }
        }

        // Unity → HTML(给 Unity 调用)
        function OnReceiveFromUnity(message) {
            /*  alert("Unity 传来的参数是:\n\n" + message); */
            console.log("从Unity接收到的消息:", message);

            const msgObject = {
                type: 'unity-message',
                data: message
            };
            try {
                window.top.postMessage(msgObject, '*');
            } catch (error) {
                console.error("发送消息失败:", error);
            }
        }


    </script>

</body>

主要就是两个方法

1、监听unity发来的消息,然后包装一下,等待发给vue

bash 复制代码
function OnReceiveFromUnity(message) {
    /*  alert("Unity 传来的参数是:\n\n" + message); */
    console.log("从Unity接收到的消息:", message);

    const msgObject = {
        type: 'unity-message',
        data: message
    };
    try {
        window.top.postMessage(msgObject, '*');
    } catch (error) {
        console.error("发送消息失败:", error);
    }
}

2、监听来自vue的消息,切片发送给unity

bash 复制代码
 window.addEventListener('message', (event) => {
		console.log("模型收到来自父窗口的消息:", event.data)
    if (event.data.type == 'call-callUnity') {
        callUnity(JSON.stringify(event.data.data));

    }
})

3 vue文件代码

bash 复制代码
<iframe style="width: 1920px;height:1080px;" id="modelRef" ref="modelRef" src="static/KEIPER_12_18/TestHtml.html" frameborder="0" @load="onModelLoad"></iframe>

load方法是模型加载后会执行,监听来自unity发送的消息

bash 复制代码
 onModelLoad() {
   window.addEventListener('message', function (event) {
        if (event.data.type == 'unity-message') {
            console.log('收到来自unity的消息:', event.data);
            this.testId = event.data.data
            this.getDialogData(this.testId)
        }
    }.bind(this));
},

4 给unity传信息

bash 复制代码
sendMessageToIframe(message) {
  const iframe = this.$refs.modelRef;
    if (!iframe) {
        console.error('无法获取iframe引用');
        return;
    }
   let newMessage = {
       type: 'call-callUnity',
       data:message
   };
    //console.log('向unity发送消息---------------vue:', newMessage);
    iframe.contentWindow.postMessage(newMessage, '*');
},
相关推荐
2分钟速写快排7 小时前
孔乙己的茴字有多少种写法?|AI 对话实时通信的三种实现
前端·javascript·github
Penge6669 小时前
JavaScript:BOM 详解
前端
梯度下降者9 小时前
Nuxt框架
vue.js·服务端渲染·全栈开发·混合渲染·nuxt框架
Penge6669 小时前
Vite vs Webpack:前端构建工具原理与实战
前端
Penge6669 小时前
前端包管理工具:npm、Yarn、pnpm 快速入门
前端
Penge66610 小时前
Sass 了解
前端
Penge66610 小时前
Webpack 打包从 0 到 1 实战笔记
前端
Penge66610 小时前
Webpack 入门:是什么、为什么需要、怎么使用?
前端
Penge66610 小时前
Ant Design(Antd)了解
前端
wangruofeng11 小时前
同一行代码,百种渲染:Asuka、React Native 与 Flutter 跨平台渲染机制深度拆解
前端·github