需求分析:
Unity webgl嵌入到前端網(wǎng)頁(yè)中,前端通過(guò)調(diào)用Unity webgl內(nèi)方法實(shí)現(xiàn)需要展示的功能,前端點(diǎn)擊Unity webgl內(nèi)的交互點(diǎn),Unity webgl返回給前端一些需要的數(shù)據(jù)。
例如:當(dāng)我們需要在三維場(chǎng)景中展示庫(kù)區(qū)中一些監(jiān)控設(shè)備的部署位置,通過(guò)點(diǎn)擊三維場(chǎng)景中的監(jiān)控按鈕打開(kāi)當(dāng)前監(jiān)控設(shè)備的實(shí)時(shí)畫(huà)面,一般情況下打開(kāi)監(jiān)控需要傳遞當(dāng)前監(jiān)控的IP或者通道號(hào),這時(shí)Unity webgl向前端返回?cái)?shù)據(jù)就用到了。
實(shí)現(xiàn)過(guò)程:
1、Unity webgl向Vue發(fā)送數(shù)據(jù)
首先,Unity webgl向前端發(fā)送數(shù)據(jù)需要定義一個(gè).jslib格式文件作為轉(zhuǎn)接,文件名自?。ńㄗh不要用中文)文件內(nèi)容如下:
mergeInto(LibraryManager.library, {
UnitySendMessage: function (eventname, data)
{
window.ReportReady(UTF8ToString(eventname), UTF8ToString(data));
} //如果多個(gè)方法需要使用逗號(hào)結(jié)尾(在此大括號(hào)后加逗號(hào)),只有一個(gè)方法不需要使用逗號(hào)
});
到此,轉(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)聽(tīng)時(shí)使用
}
private string GetButtonName()
{
string name = EventSystem.current.currentSelectedGameObject.name;
return name;
}
}
打包后打開(kāi)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對(duì)應(yīng)Unity內(nèi)定義的事件名
2、Vue向Unity發(fā)送數(shù)據(jù)
首先,Vue調(diào)用Unity的方法就比較簡(jiǎn)單了,在Unity內(nèi)定義帶參數(shù)的方法如:
using UnityEngine;
public class Test: MonoBehaviour
{
private void GetVueData(string value)
{
Debug.Log(value);
}
}
接著打開(kāi)打包后的index.html文件,在里面加入供前端調(diào)用的方法:
function GetVueMessage(obj) {
UnityInstanceV.SendMessage('MainSenceScript', 'GetVueData', JSON.stringify(obj))
//對(duì)應(yīng)的參數(shù)分別為:"Unity場(chǎng)景內(nèi)掛載腳本的物體名字","方法名",最后一個(gè)參數(shù)復(fù)制粘貼即可
}
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-751634.html
最后只需Vue調(diào)用此方法并傳遞參數(shù)就可以了,如果這篇文章幫助到你,就點(diǎn)個(gè)贊吧!文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-751634.html
到了這里,關(guān)于Unity webgl 嵌入Vue實(shí)現(xiàn)過(guò)程的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!