行业知识
Unity WebGL和JS通信
2026-11-09 13:14:43
来源:互联网转载
1.Unity调用JS方法
1.1在Assets文件夹下新建Plugins文件夹并在该文件夹下新建.jslib扩展名文件(名称无所谓)
1.2 在.jslib扩展名文件新增以下代码(标准格式)
mergeInto(LibraryManager.library, {}); 1.3 创建JS方法
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; }} 2.3 上述操作完成后打包
2.4 完成打包后在index.html中查找unityInstance
2.5 使用unityInstance调用Unity方法
unityInstance.SendMessage('场景中挂载脚本的物体名','方法名');unityInstance.SendMessage('场景中挂载脚本的物体名','方法名','方法对应参数'); 2.6 运行查看结果
上一篇:tomcat怎么优化服务器?