UnityWebGl與Vue通訊問題(及如何內(nèi)嵌Webgl至Vue)

最近有一個(gè)需求,需要把網(wǎng)頁的用戶登錄信息在unity webgl 項(xiàng)目啟動(dòng)時(shí)傳進(jìn)unity,試了很多方法都不成功,下面是最后 的解決方案

Unity

  1. 定義一個(gè)jslib文件,名字隨意,比如global.jslib,但是此文件必須放入Plugins文件夾。然后寫入以下代碼:
mergeInto(LibraryManager.library, {

    SayHello: function () {
        window.alert("Hello, world!");
    },
 
     ReportReady: function () {
       window.ReportReady();
    }
});
  1. 新建一個(gè)JsTalker.cs文件測(cè)試,將其掛載在一個(gè)名稱為JsTalker的空物體上
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;

public class JsTalker : MonoBehaviour
{
    [DllImport("__Internal")]
    private static extern void SayHello();

    [DllImport("__Internal")]
    private static extern string ReportReady();

    public Text text;
    void Start()
    {
        ReportReady();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyUp(KeyCode.H))
        {
            SayHello();
        }

    }
    public void SetToken(string token)
    {
        text.text = token;
    }
}


將unity工程打包發(fā)布,所有文件放到Vue的public目錄下


image.png

Vue

  1. (假設(shè)使用VueCli3建立工程)安裝vue-unity-webgl
    yarn add vue-unity-webgl --save
  2. App.vue
<template>
  <unity
    src="/Dist/Build/Dist.json"
    width="1000"
    height="600"
    unityLoader="/Dist/Build/UnityLoader.js"
    ref="unityvue"
  ></unity>
</template>

<script>
import Unity from "vue-unity-webgl"; 
export default {
  components: { Unity },
  name: "App",
  created() {
    localStorage.setItem("token", "adsdasdasdads");

    window.ReportReady = () => {
      alert("report ready event received"); 
      this.$refs.unityvue.message("JsTalker", "SetToken", localStorage.token);
    };
  }
};
</script>

運(yùn)行yarn serve; 可以看到token已經(jīng)被傳進(jìn)unity

image.png

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容