发送post请求
public string url = "http://XXXXXXXXX";// 请求数据public string postData = "{\"user_id\": 1}";// Start is called before the first frame updatevoid Start(){// Post();StartCoroutine(PostRequestCoroutine(url, postData));}private IEnumerator PostRequestCoroutine(string url, string jsonData){// 创建 UnityWebRequestUnityWebRequest 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);
};