Search code examples
javascriptunity-game-engineunity-webgl

Calling javascript string function on browser from Unity returns null


I have a WebGL unity project which attempts to execute javascript code on the browser and return a value.

I have the following .jslib file in my Assets/Plugins/WebGL folder:

var BrowserPlugin = {
    GetEndpointURL: function()
    {
        var endpoint = window.itd.getEndpointUrl();

        console.log("endpoint: " + endpoint);

        return endpoint;
     }
};

mergeInto(LibraryManager.library, BrowserPlugin);

In my c# code in unity, I import the dll and call my javascript method like so:

[DllImport("__Internal")]
private static extern string GetEndpointURL();

string endpointURL = GetEndpointURL();

The problem is, in my c# code the endpointUrl variable is always null. However, in my browser console, I can clearly see the correct value is logged in the browser javascript before I return it. What is causing this value to come back to unity as null?


Solution

  • This is your code:

    GetEndpointURL: function()
    {
        var endpoint = window.itd.getEndpointUrl();
        console.log("endpoint: " + endpoint);
        return endpoint;
    }
    

    You cannot return string (endpoint) directly. You have to create a buffer to hold that string and this process includes allocating memory with _malloc and copying old string to that new memory location with writeStringToMemory.

    GetEndpointURL: function()
    {
        var endpoint = window.itd.getEndpointUrl();
        console.log("endpoint: " + endpoint);
    
        var buffer = _malloc(lengthBytesUTF8(endpoint) + 1);
        writeStringToMemory(endpoint, buffer);
        return buffer;
    }