unity3d 为什么Unity WebGL构建捕获错误“ReferenceError:未定义MyMethodName”?

hfyxw5xn  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(209)

我想在Unity中调用javascript函数。我创建了一个文件夹“Plugins”,如https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html中所述,并创建了一个扩展名为.jslib的javascript文件,并放入下一个代码:
`

mergeInto(LibraryManager.library, {
    GetBrowserQueryString: () => {
        const qs = window.location.search;
        const bufferSize = lengthBytesUTF8(qs) + 1;
        const buffer = _malloc(bufferSize);

        stringToUTF8(qs, buffer, bufferSize);

        return buffer;
    },
    GetVkUserId: () => {
        const qs = window.location.search;
        const match = qs.match(/vk_user_id=(\d+)/);

        const vkUserIdString = match[1];
        const bufferSize = lengthBytesUTF8(vkUserIdString) + 1;
        const buffer = _malloc(bufferSize);

        stringToUTF8(vkUserIdString, buffer, bufferSize);

        return buffer;
    }
});

`
当我在浏览器中启动构建应用程序时,我看到错误“ReferenceError:没有定义_GetBrowserQueryString”。如何修复?我做错了什么?
在jslib文件的检查器中,我已经检查了WebGL检查。
C#代码所在的位置尝试执行javascript代码:

public class SocketManager : MonoBehaviour {
    ... bla bla bla
    
    [DllImport("__Internal")]
    private static extern string GetBrowserQueryString();
    [DllImport("__Internal")]
    private static extern string GetVkUserId();

    private void Awake() {
        string vkQuery = GetBrowserQueryString();
        string vkUserId = GetVkUserId();
        ... bla bla bla
    }
}
5rgfhyps

5rgfhyps1#

错误在于我使用了箭头函数而不是通常的函数命名..... Unity不知道javascript中的箭头函数:(
修正:

mergeInto(LibraryManager.library, {
GetQueryString: function() {
    const qs = window.location.search;
    const bufferSize = lengthBytesUTF8(qs) + 1;
    const buffer = _malloc(bufferSize);

    stringToUTF8(qs, buffer, bufferSize);

    return buffer;
},
GetVkUserId: function() {
    const qs = window.location.search;
    const match = qs.match(/vk_user_id=(\d+)/);

    const vkUserIdString = match[1];
    const bufferSize = lengthBytesUTF8(vkUserIdString) + 1;
    const buffer = _malloc(bufferSize);

    stringToUTF8(vkUserIdString, buffer, bufferSize);

    return buffer;
}

});

相关问题