vue项目接入unity3D模块并进行数据通信

一、添加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>

展示效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43923659/article/details/128864967