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());
    }
}

 源碼地址:https://github.com/kingBook/unityWebGLCallJS


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM