mergeInto(LibraryManager.library, {
Test: function () {
alert("Unity调用JS");
},
// 多个方法可用(,)逗号隔开
TestArgument: function(str)
{
var message=UTF8ToString(str);
alert(message);
},
});
1.4 调用JS方法(新建空物体挂载在脚本)
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
public class TestJS : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void Test();
[DllImport("__Internal")]
private static extern void TestArgument(string message);
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
Test();
}
if (Input.GetKeyDown(KeyCode.B))
{
TestArgument("测试Unity调用JS传参方法");
}
}
}
1.5 打包并运行(中文乱码问题不用管,运行结果正确)
2. JS调用Unity方法
2.1 在Unity Editor下创建空物体并挂载上调用的脚本
2.2 创建方法(随便创建即可,方法必须为public)
using TMPro;
using UnityEngine;
public class TestJSInvokeUnity : MonoBehaviour
{
public GameObject cube;
public TMP_Text infoText;
public void ShowCube()
{
cube.SetActive(true);
}
public void ShowText(string info)
{
infoText.text = info;
}
}