unity打包web,发送post请求,获取地址栏参数,解决TypeError:s.replaceAll is not a function
发送post请求
public string url = "http://XXXXXXXXX";
// 请求数据
public string postData = "{\"user_id\": 1}";
// Start is called before the first frame update
void Start()
{
// Post();
StartCoroutine(PostRequestCoroutine(url, postData));
}
private IEnumerator PostRequestCoroutine(string url, string jsonData)
{
// 创建 UnityWebRequest
UnityWebRequest request = new UnityWebRequest(url, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(jsonData);
// 设置请求体和头部
request.uploadHandler = new UploadHandlerRaw(jsonToSend);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
// 发送请求
yield return request.SendWebRequest();
// 检查响应
if (request.result == UnityWebRequest.Result.Success)
{
Debug.Log("Response: " + request.downloadHandler.text);
}
else
{
Debug.LogError("Error: " + request.error);
}
}
如果请求是http协议,需要配置
打包web后会受到跨域的影响
获取地址栏参数
打包后,会有一个index.html文件,原理是通过js获取地址栏参数,然后使用unity的js实例,向游戏内的一个对象发送消息,调用一个方法并传递参数。
在index.html里,添加获取地址栏参数方法:
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
在创建unity的js实例后,添加调用方法:
script.onload = () => {
createUnityInstance(canvas, config, (progress) => {
document.querySelector("#unity-progress-bar-full").style.width = 100 * progress + "%";
}).then((unityInstance) => {
document.querySelector("#unity-loading-bar").style.display = "none";
document.querySelector("#unity-fullscreen-button").onclick = () => {
unityInstance.SetFullscreen(1);
};
// 获取参数
var param1 = getUrlParameter('uid');
var param2 = getUrlParameter('t');
// 调用游戏对象Controller上的ReceiveParameters方法,传递字符串参数
unityInstance.SendMessage('Controller', 'ReceiveParameters', param1 + ',' + param2);
}).catch((message) => {
alert(message);
});
};
解决TypeError:s.replaceAll is not a function
如果浏览器版本较低,运行时,会报错:TypeError:s.replaceAll is not a function
解决方法很简单,在index.html的js代码最开始,直接为字符串类型定义replaceAll方法
String.prototype.replaceAll = function(search, replacement) {
const pattern = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); // 转义字符
const reg = new RegExp(pattern, 'g'); // 创建全局正则表达式
return this.replace(reg, replacement);
};
其他一些错误解决方法:.gzip
原文地址:https://blog.csdn.net/li53957105/article/details/144287033
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!