在UnityWebgl平台上,经常会从前端获取参数,如token、host等,使用jslib与前端js代码进行交互。只需要在Plugins文件夹中创建一个xxx.jslib文件即可。
jslib文件代码如下:
mergeInto(LibraryManager.library, {
getUrlParams: function (defaultValue) {
var name = Pointer_stringify(defaultValue);
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r != null){
var returnStr = unescape(r[2]);
var bufferSize = lengthBytesUTF8( returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
}
else return null; //返回参数值
},
});
想要在Unity中调用jslib中的getUrlParams
方法,只需要在Unity中合适的地方添加以下代码后调用即可:
[DllImport("__Internal")]
private static extern string getUrlParams(string name);
注意:
在Unity中向js传递字符串时需要在js中使用Pointer_stringify(str)
进行转换。
在js中向Unity返回字符串的时候也需要进行如下操作:
var bufferSize = lengthBytesUTF8( returnStr) + 1;
var buffer = _malloc(bufferSize);
stringToUTF8(returnStr, buffer, bufferSize);
return buffer;
这里封装了一下UnityWebRequest,只需要提供对应的参数和回调即可进行数据请求,包括可选择对数据进行Base64加密。
public enum UnityWebRequestType
{
POST,
GET
}
///
/// 发送HTTP数据
///
/// 请求类型
/// 请求地址
/// 传输的数据
/// 发送数据是否需要Base64加密
/// 获取数据是否需要Base64加密
/// 失败回调
/// 成功回调
/// 额外添加的头名称
/// 额外添加的头值
public void SendHttpMessage(UnityWebRequestType type, string url, string jsonData, bool sendBase64, bool getBase64, UnityAction failureCallBack, UnityAction<string> successCallBack, string[] otherHeaderName, string[] otherHeaderValue)
{
StartCoroutine(WebRequest(type, url, jsonData, sendBase64, getBase64, failureCallBack, successCallBack, otherHeaderName, otherHeaderValue));
}
private IEnumerator WebRequest(UnityWebRequestType type, string url, string jsonData, bool sendBase64, bool getBase64, UnityAction failureCallBack, UnityAction<string> successCallBack, string[] otherHeaderName, string[] otherHeaderValue)
{
Debug.Log(type.ToString() + "\t" + url + "\t" + jsonData);
if (sendBase64)
{
jsonData = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonData));
}
byte[] body = Encoding.UTF8.GetBytes(jsonData);
UnityWebRequest unityWeb = new UnityWebRequest(@url, type.ToString());
unityWeb.uploadHandler = new UploadHandlerRaw(body);
unityWeb.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
//unityWeb.SetRequestHeader("Authorization", "Bearer " + token);
if (otherHeaderName != null)
{
for (int i = 0; i < otherHeaderName.Length; i++)
{
unityWeb.SetRequestHeader(otherHeaderName[i], otherHeaderValue[i]);
}
}
unityWeb.downloadHandler = new DownloadHandlerBuffer();
yield return unityWeb.SendWebRequest();
if (unityWeb.isNetworkError || unityWeb.isHttpError)
{
Debug.LogError("UnityWebRequest 请求失败:" + unityWeb.error);
failureCallBack?.Invoke();
yield break;
}
if (unityWeb.isDone)
{
string result = unityWeb.downloadHandler.text;
if (getBase64)
{
byte[] c = Convert.FromBase64String(result);
result = Encoding.UTF8.GetString(c);
}
Debug.Log("UnityWebRequest 请求成功:" + result);
successCallBack?.Invoke(result);
}
}
///
/// 发送表单数据
///
/// 请求地址
/// 表单Key数据
/// 表单Value数据
/// 发送数据是否需要Base64加密
/// 获取数据是否需要Base64加密
/// 失败回调
/// 成功回调
public void SendHttpMessageByForm(string url, string[] fromKey, string[] fromValue, bool sendBase64, bool getBase64, UnityAction failureCallBack, UnityAction<string> successCallBack)
{
StartCoroutine(WebRequestFrom( url, fromKey, fromValue, sendBase64, getBase64, failureCallBack, successCallBack ));
}
private IEnumerator WebRequestFrom( string url,string[] fromKey, string[] fromValue ,bool sendBase64, bool getBase64, UnityAction failureCallBack, UnityAction<string> successCallBack)
{
WWWForm form = new WWWForm();
if (fromKey != null)
{
for (int i = 0; i < fromKey.Length; i++)
{
if (sendBase64)
{
fromValue[i] = Convert.ToBase64String(Encoding.UTF8.GetBytes(fromValue[i]));
}
Debug.Log("表单添加字段:" + fromKey[i] + "\t" + fromValue[i]);
form.AddField(fromKey[i], fromValue[i]);
}
}
UnityWebRequest unityWeb = UnityWebRequest.Post(@url, form);
unityWeb.downloadHandler = new DownloadHandlerBuffer();
yield return unityWeb.SendWebRequest();
if (unityWeb.isNetworkError || unityWeb.isHttpError)
{
Debug.LogError("UnityWebRequest 请求失败:" + unityWeb.error);
failureCallBack?.Invoke();
yield break;
}
if (unityWeb.isDone)
{
string result = unityWeb.downloadHandler.text;
if (getBase64)
{
byte[] c = Convert.FromBase64String(result);
result = Encoding.UTF8.GetString(c);
}
Debug.Log("UnityWebRequest 请求成功:" + result);
successCallBack?.Invoke(result);
}
}