unity WegGL 调用js
test.jslib文件,必须放到Assets/Plugins下,这里是:Assets/Plugins/WebGL
mergeInto(LibraryManager.library, { Hello: function () { window.alert("Hello, world!"); }, HelloString: function (str) { //这里使用Pointer_stringify方法转换unity传递过来的字符串 window.alert(Pointer_stringify(str)); }, PrintFloatArray: function (array, size) { for(var i = 0; i < size; i++){ //遍历float数组使用HEAPF32,更多类型:HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64 console.log(HEAPF32[(array >> 2) + i]); } }, AddNumbers: function (x, y) { //这里unity传递过来int类型数字,不需要转换 return x + y; }, //返回一个字符串到unity StringReturnValueFunction: function () { var returnStr = "bla"; var bufferSize = lengthBytesUTF8(returnStr) + 1; var buffer = _malloc(bufferSize); stringToUTF8(returnStr, buffer, bufferSize); return buffer; }, BindWebGLTexture: function (texture) { GLctx.bindTexture(GLctx.TEXTURE_2D, GL.textures[texture]); }, });
callJSTest.cs文件,绑定到任意GameObject中。
using System.Runtime.InteropServices; using UnityEngine; public class callJSTest : MonoBehaviour { [DllImport("__Internal")] private static extern void Hello(); [DllImport("__Internal")] private static extern void HelloString(string str); [DllImport("__Internal")] private static extern void PrintFloatArray(float[] array, int size); [DllImport("__Internal")] private static extern int AddNumbers(int x, int y); [DllImport("__Internal")] private static extern string StringReturnValueFunction(); [DllImport("__Internal")] private static extern void BindWebGLTexture(int texture); void Start() { Hello(); HelloString("This is a string."); float[] myArray = new float[10]; PrintFloatArray(myArray, myArray.Length); int result = AddNumbers(5, 7); Debug.Log(result); Debug.Log(StringReturnValueFunction()); var texture = new Texture2D(0, 0, TextureFormat.ARGB32, false); BindWebGLTexture(texture.GetNativeTextureID()); } }