test.jslib文件,必須放到Assets/Plugins下,這裏是:Assets/Plugins/WebGLgit
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中。github
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()); } }