我现在用的unity2018版本的调用JS的API:Application.ExternalCall 过时了,官方给出了另一种方案:https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
现在的这种方式可以传递各种返回值,官方文档上写的很详细,我简单的再描述一下这个过程:
- 首先需要写一个JS的脚本,主要是调用mergeInto();方法,第一个参数不用变,第二个参数就是JS的方法集合。写完之后将这个文件的后缀改为.jslib,放到Plugins文件夹中
mergeInto(LibraryManager.library,
{
Hello: function ()
{
window.alert("Hello, world!");
},
HelloString: function (str)
{
window.alert(Pointer_stringify(str));
},
HelloFloat: function ()
{
return 1;
},
});
2.C#脚本
using UnityEngine;
using System.Runtime.InteropServices;
public class TestJS : MonoBehaviour
{
[DllImport("__Internal")]
private static extern void Hello();
[DllImport("__Internal")]
private static extern void HelloString(string str);
[DllImport("__Internal")]
private static extern float HelloFloat();
void Start()
{
Hello();
HelloString("This is a string.");
}
void OnGUI()
{
GUIStyle gUIStyle = new GUIStyle();
gUIStyle.fontSize = 20;
float f = HelloFloat();
GUI.Label(new Rect(500, 200, 500, 500), f.ToString(), gUIStyle);
}
}
效果图:
最后说一下这种方式的缺点:就是发布之后就没法在外面更改,一旦方法要改动,就只能改完之后重新发布了。。。