使用Unity發布WebGL項目免不了要與Js進行通信,所以整理下相關知識。
一 Unity調用Js方法
1.棄用的方法
(1)在發布的WebGL項目的index.html添加Exit函數:
function Exit() { alert("UnityToWeb") }
(2)如果想在Unity中調用方法,添加代碼:
Application.ExternalCall("Exit");//調用Js的Exit方法
2.新方法
(1) 新建文件夾Plugins
(2) 文件夾新建.jslib文件,這里創建__Internal.jslib文件
添加代碼
mergeInto(LibraryManager.library, {
Hello: function (obj) {
window.alert("Hello, world!");
Exit();//調用Js方法
},
});
(3)c#文件
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public class UnityToWeb : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void Hello();
public void CallJs()
{
// Unity call web
Hello();
}
}
(5)在發布的WebGL項目的index.html添加Exit函數:
function Exit() { alert("UnityToWeb") }
二 Js調用Unity方法
1.在場景中新建一個Cube,然后在新建腳本WebToUnity,掛載到Cube身上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WebWithUnity : MonoBehaviour
{
public Text text;
// Start is called before the first frame update
void Start()
{
text.text = "Cobe當前位置:\nx:" + transform.position.x + " y:"+transform.position.y + " z:"+transform.position.z;
}
public void JsToUnity(string str)
{
transform.position = new Vector3(transform.position.x + 1,transform.position.y);
text.text = "Cobe當前位置:\nx:" + transform.position.x + " y:" + transform.position.y + " z:" + transform.position.z;
}
}
做一個這樣的UI
給Text賦值,給按鈕添加上點擊事件觸發CallJs()
2.這里,我們要在Js中調用JsToUnity這個函數,將項目打包后,修改index.html文件。
在index.html的script中修改如下
unityInstance.SendMessage(objectName, methodName, value);
objectName是場景中對象的名稱,比如Cube
methodName:是腳本中當前附加到該對象的方法的名稱
value:給方法里的參數傳值,可以是字符串,數字或為空
var instance;
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
progressBarFull.style.width = 100 * progress + "%";
}).then((unityInstance) => {
loadingBar.style.display = "none";
fullscreenButton.onclick = () => {
unityInstance.SetFullscreen(1);
};
instance = unityInstance;
}).catch((message) => {
alert(message);
});
};
document.body.appendChild(script);
function Exit() { alert("UnityToWeb") }//Exit方法
function TestSend() { instance.SendMessage("Cube", "JsToUnity","string"); }