詳解Unity webgl 嵌入Vue實現(xiàn)過程
需求分析:
Unity webgl嵌入到前端網(wǎng)頁中,前端通過調(diào)用Unity webgl內(nèi)方法實現(xiàn)需要展示的功能,前端點擊Unity webgl內(nèi)的交互點,Unity webgl返回給前端一些需要的數(shù)據(jù)。
例如:當我們需要在三維場景中展示庫區(qū)中一些監(jiān)控設備的部署位置,通過點擊三維場景中的監(jiān)控按鈕打開當前監(jiān)控設備的實時畫面,一般情況下打開監(jiān)控需要傳遞當前監(jiān)控的IP或者通道號,這時Unity webgl向前端返回數(shù)據(jù)就用到了。
實現(xiàn)過程:
1、Unity webgl向Vue發(fā)送數(shù)據(jù)
首先,Unity webgl向前端發(fā)送數(shù)據(jù)需要定義一個.jslib格式文件作為轉(zhuǎn)接,文件名自?。ńㄗh不要用中文)文件內(nèi)容如下:

mergeInto(LibraryManager.library, {
UnitySendMessage: function (eventname, data)
{
window.ReportReady(UTF8ToString(eventname), UTF8ToString(data));
} //如果多個方法需要使用逗號結尾(在此大括號后加逗號),只有一個方法不需要使用逗號
});到此,轉(zhuǎn)接文件已經(jīng)定義好了
接著在Unity腳本中添加 using System.Runtime.InteropServices; 引用(用于COM互操作),
代碼如下:
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Test: MonoBehaviour
{
[DllImport("__Internal")]
private static extern void UnitySendMessage(string eventname, string data);//方法名及參數(shù)和轉(zhuǎn)接的.jslib文件中的一樣
private Button button;
private void Awake()
{
button.onClick.AddListener(SendMessage);
}
private void SendMessage()
{
UnitySendMessage("getbuttonname",GetButtonName());//事件名自己命名即可,前端在監(jiān)聽時使用
}
private string GetButtonName()
{
string name = EventSystem.current.currentSelectedGameObject.name;
return name;
}
}打包后打開index.html文件加入此段代碼:
window.ReportReady = function (eventname, data) {
var initD = { detail: { data } }
var evt = new CustomEvent(eventname, initD)
window.top.dispatchEvent(evt)
}如圖:

最后在Vue mounted中加入即可
window.addEventListener('getbuttonname', this.uinityEvent, false)//getbuttonname對應Unity內(nèi)定義的事件名2、Vue向Unity發(fā)送數(shù)據(jù)
首先,Vue調(diào)用Unity的方法就比較簡單了,在Unity內(nèi)定義帶參數(shù)的方法如:
using UnityEngine;
public class Test: MonoBehaviour
{
private void GetVueData(string value)
{
Debug.Log(value);
}
}接著打開打包后的index.html文件,在里面加入供前端調(diào)用的方法:
function GetVueMessage(obj) {
UnityInstanceV.SendMessage('MainSenceScript', 'GetVueData', JSON.stringify(obj))
//對應的參數(shù)分別為:"Unity場景內(nèi)掛載腳本的物體名字","方法名",最后一個參數(shù)復制粘貼即可
}
最后只需Vue調(diào)用此方法并傳遞參數(shù)就可以了,如果這篇文章幫助到你,就點個贊吧!
到此這篇關于Unity webgl 嵌入Vue實現(xiàn)過程的文章就介紹到這了,更多相關Unity webgl 嵌入Vue內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue Element前端應用開發(fā)之echarts圖表
在我們做應用系統(tǒng)的時候,往往都會涉及圖表的展示,綜合的圖表展示能夠給客戶帶來視覺的享受和數(shù)據(jù)直觀體驗,同時也是增強客戶認同感的舉措之一2021-05-05

