最近有一个需求,需要把网页的用户登录信息在unity webgl 项目启动时传进unity,试了很多方法都不成功,下面是最后 的解决方案
Unity
- 定义一个jslib文件,名字随意,比如
global.jslib
,但是此文件必须放入Plugins
文件夹。然后写入以下代码:
mergeInto(LibraryManager.library, {
SayHello: function () {
window.alert("Hello, world!");
},
ReportReady: function () {
window.ReportReady();
}
});
- 新建一个
JsTalker.cs
文件测试,将其挂载在一个名称为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工程打包发布,所有文件放到Vue的public目录下
image.png
Vue
- (假设使用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>
运行yarn serve
; 可以看到token已经被传进unity
网友评论