一、添加unity工程
unity工程师会提供一个前端可使用的包,将其放在vue项目的public下,我这里以unity文件夹定名

二、在项目中创建iframe标签并引入index.html文件
- <iframe id="iframe" ref="iframe" src="/unity/index.html" width="100%" height="100%" frameborder="0" scrolling="auto" />
复制代码 三、修改public > unity > index.html文件,制定发送到web端变乱

- // unity按钮点击发送事件
- function UIClick(btnname){
- window.top.dispatchEvent(new CustomEvent('UIClick', { detail: { name: btnname } }))
- }
复制代码 四、在引入unity的vue文件中监听接收unity发送变乱, 由于我使用了页面缓存以是在activated()生命周期中监听,根据业务必要也可以在mounted()生命周期中监听
- activated() {
- window.addEventListener('UIClick', this.unityWatch)
- },
- // 或者
- mounted() {
- window.addEventListener('UIClick', this.unityWatch)
- },
-
- methods: {
- // unity发送事件执行
- unityWatch(obj) {
- console.log(obj.detail); // 这里写需要的后续js逻辑
- },
- }
复制代码 五、vue发送变乱给unity
- unitySendMessage() {
- /** 参数:
- * 1. unity定义的对象(每个unity工程师喜欢的名字不一样)
- * 2. 调用unity的方法名字
- * 3. unity接收的参数
- */
- this.$refs.iframe.contentWindow.unityInstance.SendMessage('WebInvoker', 'Unity_InsertNaviPoint', '这是参数')
- },
复制代码 六、烧毁监听
- 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() {
- // 监听unity发送事件
- window.addEventListener('UIClick', this.unityWatch)
- },
- methods: {
- // 调用unity内部事件
- unitySendMessage() {
- /** 参数:
- * 1. unity定义的对象(每个unity工程师喜欢的名字不一样)
- * 2. 调用unity的方法名字
- * 3. unity接收的参数
- */
- this.$refs.iframe.contentWindow.unityInstance.SendMessage('WebInvoker', 'Unity_InsertNaviPoint', this.nodeList.length)
- },
- // unity发送事件执行
- unityWatch(obj) {
- console.log(obj.detail); // 这里写需要的后续js逻辑
- },
- },
- deactivated() {
- window.removeEventListener('UIClick', this.unityWatch)
- }
- }
- </script>
复制代码 展示结果

来源:https://blog.csdn.net/weixin_43923659/article/details/128864967
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |