Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 851
AM031447 Avatar asked Oct 14 '25 16:10

AM031447


1 Answers

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;
}
like image 135
Programmer Avatar answered Oct 17 '25 04:10

Programmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!