Vue项目使用UnityWebGl和交互通信-案例

基础

将unity导出文件放在vue项目的public目录下

效果 

方式一

插件方式 

npm install vue-unity-webgl --save

使用

注意,目录问题

<template>
  <div class="about">
    <h1 @click="show">Unity components | 插件方式</h1>
    <Unity
      src="/Build/WebGL.json"
      width="1000"
      height="600"
      unityLoader="/Build/UnityLoader.js"
      ref="unityvue"
      class="main-unity"
    ></Unity>
  </div>
</template>
<script>
import Unity from "vue-unity-webgl";
export default {
  components: { Unity },

  created() {
     // window.ReportReady = () => {};
  },
  methods: {
    // 和Unity 通信
    show() {
      // this.$refs.unityvue.message("GameObject", "ViewCard", "发送内容");
      this.$refs.unityvue.message("GameObject", "ViewCard", "7");
    },
  },
};
</script>

方式二

原生方式

在index.html文件引入unity相关js文件

<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  <!-- <link rel="stylesheet" href="<%= BASE_URL %>TemplateData/style.css"> -->
  <title>
    <%= htmlWebpackPlugin.options.title %>
  </title>
</head>

<body>
  <noscript>
    <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
        Please enable it to continue.</strong>
  </noscript>
  <div id="app"></div>
  <!-- built files will be auto injected -->
  <script src="<%= BASE_URL %>TemplateData/UnityProgress.js"></script>
  <script src="<%= BASE_URL %>Build/UnityLoader.js"></script>
  <!-- 使用vue的方式 -->
  <!-- <script>
    var unityInstance = UnityLoader.instantiate("unityContainer", "Build/WebGL.json", { onProgress: UnityProgress });
    setTimeout(() => unityInstance.SendMessage("GameObject", "ViewCard", "7"), 4000);
  </script> -->
</body>

</html>

使用

<template>
  <div class="unity">
    <div id="unityContainer" style="width: 960px; height: 600px"></div>
  </div>
</template>

<script>
let { UnityLoader, UnityProgress } = window;
export default {
  name: "UnityWebgl",
  // props: {
  //   // 卡牌编号 0-7
  //   ids: {
  //     type: String,
  //     required: true,
  //     default() {
  //       return "1";
  //     },
  //   },
  // },
  data() {
    return {};
  },
  mounted() {
    this.initUnity();
  },
  methods: {
    initUnity() {
      window.UnityInstance = UnityLoader.instantiate(
        "unityContainer",
        "/Build/WebGL.json",
        { onProgress: UnityProgress }
      );
      setTimeout(() => this.showCardId(3), 4000);
    },
    showCardId(id) {
      // 其他页面也可以调用
      window.UnityInstance.SendMessage("GameObject", "ViewCard", String(id));
    },
  },
  destroyed() {
    console.log("页面卸载");
  },
};
</script>

<style scoped lang="scss">
</style>

和unity通信 

window.UnityInstance.SendMessage("GameObject", "ViewCard", "4");

posted @ 2022-01-10 08:43  JackieDYH  阅读(484)  评论(0编辑  收藏  举报  来源