Home > Enterprise >  Why Unity WebGL build catched error "ReferenceError: MyMethodName is not defined"?
Why Unity WebGL build catched error "ReferenceError: MyMethodName is not defined"?

Time:12-06

I want to call javascript function in unity. I created a folder "Plugins" like explained in https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html and create a javascript file with extension .jslib and put inside next code:

`

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

`

When i start the build application in browser i see the error "ReferenceError: _GetBrowserQueryString is not defined". How to fix it? What i do wrongly?

In Inspector of jslib file i already checked the WebGL check.

C# code where a trying execute javascript code:

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
    }
}

CodePudding user response:

The mistake was that I used arrow functions instead of the usual function naming..... Unity does not know about arrow functions in javascript :(

Fixes:

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

});

  • Related