在unity的Plugins文件夹下,创建.jslib文件(可先创建txt,然后将txt打开,另存为.jslib),名字随意。例如: Test.jslib
Test.jslib内容如下:(Hello名字在unity中使用,TestSend名字在Web中使用。)
mergeInto(LibraryManager.library, {
Hello: function (str) {
TestSend("Hello, world!");
},
});
脚本需要引入命名空间:using System.Runtime.InteropServices;
using System.Runtime.InteropServices;
using UnityEngine;
public class Test : MonoBehaviour
{
//声明和jslib文件关联的Hello()方法
[DllImport("__Internal")]
private static extern void Hello();
void Start() {
//调用测试,在unity脚本任意地方,调用hello方法都可以。
Hello();
}
}
选中Webgl平台,打包修改index.html
在html代码的中添加如下代码:
function TestSend(s)
{
alert(s);
}
方法名TestSend与.jslib文件function内方法名相同,参数数量相同。
即可发现进入场景后,执行了Start()中的Hellow方法,从而调用了web中新定义的TestSend()方法。弹出alert对话框。
5.如需传递字符串,jslib代码修改如下:
mergeInto(LibraryManager.library, {
Hello: function (str) {
TestSend(Pointer_stringify(str));
},
});
传递其他数据结构,请查看上方官方手册。
public void GetFromWeb(string str)
{
Debug.Log(str);
}
并将脚本挂在到场景中。
使用gameInstance.SendMessage(“GameObject”,“GetFromWeb”,s);调用unity内方法。
SendMessage中第一个参数为挂在1中脚本的物体名称,第二个参数为方法名称,第三个参数是对应的方法参数。
为方便测试,将调用脚本写在unity向web发送消息时用的脚本里。
index.html修改如下
function TestSend(s)
{
alert(s);
gameInstance.SendMessage("GameObject","GetFromWeb",s);
}
写在普通的js方法里,通过html调用也是一样的。
3.测试
一开始和第一部分一样,打开webgl网页,执行了unity的Start()中的Hello方法,从而调用了web中定义的TestSend()方法:1.alert(s); 弹出写着参数s的alert对话框。然后执行 2. gameInstance.SendMessage("GameObject","GetFromWeb",s);调用unity场景中名为GameObject物体上脚本里的GetFromWeb()方法,并将参数s传入。 按F12打开控制台,即可看见输出的参数s。
原文链接:https://blog.csdn.net/boyzhengui/article/details/114374111