最近有一個(gè)需求,需要把網(wǎng)頁的用戶登錄信息在unity webgl 項(xiàng)目啟動(dòng)時(shí)傳進(jìn)unity,試了很多方法都不成功,下面是最后 的解決方案
Unity
- 定義一個(gè)jslib文件,名字隨意,比如
global.jslib,但是此文件必須放入Plugins文件夾。然后寫入以下代碼:
mergeInto(LibraryManager.library, {
SayHello: function () {
window.alert("Hello, world!");
},
ReportReady: function () {
window.ReportReady();
}
});
- 新建一個(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
- (假設(shè)使用VueCli3建立工程)安裝vue-unity-webgl
yarn add vue-unity-webgl --save - 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