本文介绍了从UnityWebGL jslib返回字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jslib获取 url参数

I want use jslib to get url parameter

这样的代码

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

从jslib运行警报时,我看到警报中显示了正确的字符串,但UGUI文本什么也不显示.

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

为什么会这样?

推荐答案

要将string从Javascript返回到Unity,您必须使用_malloc分配内存,然后使用writeStringToMemoryv1[1]变量放入新分配的内存中,然后将其返回.

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

writeStringToMemory函数似乎已已弃用现在,但是您仍然可以使用stringToUTF8做同样的事情,并在其第三个参数中证明字符串的大小.

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

这篇关于从UnityWebGL jslib返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 00:57