Search code examples
javascripthtmlunity-game-enginegetunity-webgl

Return string from UnityWebGL jslib


I want use jslib to get url parameter

code like this

jslib

  GetUrl: function(){
  var s ="";
  var strUrl = window.location.search;
  var getSearch = strUrl.split("?");
  var getPara = getSearch[1].split("&");
  var v1 = getPara[0].split("=");
        alert(v1[1]);
   return v1[1];
  },
});

c#

[DllImport("__Internal")]
public static extern string GetUrl();


void Start () {
    TextShow.text = GetUrl();
}

When run alert from jslib , I see right string show in alert but UGUI Text shows nothing.

Why did this happen?


Solution

  • To return string from Javascript to Unity, you must use _malloc to allocate memory then writeStringToMemory to copy the string data from your v1[1] variable into the newly allocated memory then return that.

    GetUrl: function()
    {
      var s ="";
      var strUrl = window.location.search;
      var getSearch = strUrl.split("?");
      var getPara = getSearch[1].split("&");
      var v1 = getPara[0].split("=");
      alert(v1[1]);
    
    
       //Allocate memory space
       var buffer = _malloc(lengthBytesUTF8(v1[1]) + 1);
       //Copy old data to the new one then return it
       writeStringToMemory(v1[1], buffer);
       return buffer;
    }
    

    The writeStringToMemory function seems to be deprecated now but you can still do the-same thing with stringToUTF8 and proving the size of the string in its third argument.

    GetUrl: function()
    {
      var s ="";
      var strUrl = window.location.search;
      var getSearch = strUrl.split("?");
      var getPara = getSearch[1].split("&");
      var v1 = getPara[0].split("=");
      alert(v1[1]);
    
    
       //Get size of the string
       var bufferSize = lengthBytesUTF8(v1[1]) + 1;
       //Allocate memory space
       var buffer = _malloc(bufferSize);
       //Copy old data to the new one then return it
       stringToUTF8(v1[1], buffer, bufferSize);
       return buffer;
    }