求助:Unity中WWW已过时,改用UnityWebRequest后代码无法运行
问题排查与修复方案
先明确你现有代码的几个核心问题:
- 语法错误:
UnityWebRequestweb缺少空格,应该写成UnityWebRequest web - 请求逻辑不匹配:原WWW代码是POST表单提交创建用户,你写的UnityWebRequest用了GET请求,还错误指向了登录接口(
Login.php),参数拼接里的&&也应该是& - 未完成UnityWebRequest完整流程:没有调用
SendWebRequest()发起请求,也没处理响应、错误和资源释放
以下是对应原创建用户功能的正确UnityWebRequest实现:
public IEnumerator CO_Createuser(string user, string email, string pass, string repass, Action<Response> response) { // 构建表单数据,和原WWWForm逻辑一致 WWWForm form = new WWWForm(); form.AddField("user", user); form.AddField("email", email); form.AddField("pass", pass); form.AddField("repass", repass); // 创建POST请求,对应原接口地址 using (UnityWebRequest web = UnityWebRequest.Post("http://localhost:80/Game/createuser.php", form)) { // 发起请求并等待完成 yield return web.SendWebRequest(); // 处理错误情况 if (web.result != UnityWebRequest.Result.Success) { Debug.LogError($"请求失败: {web.error}"); response?.Invoke(null); // 或者返回自定义错误Response yield break; } // 处理响应内容,和原逻辑一致 Debug.Log(web.downloadHandler.text); Response result = JsonUtility.FromJson<Response>(web.downloadHandler.text); response?.Invoke(result); } // using块会自动释放UnityWebRequest资源,无需手动Dispose }
关键说明:
- 用
using包裹UnityWebRequest,确保请求完成后自动释放资源,避免内存泄漏 - 用
UnityWebRequest.Post直接适配表单提交,和原WWW的POST逻辑完全对齐 - 新增了错误处理分支,捕获请求失败的情况(比如网络问题、接口报错)
- 响应内容通过
web.downloadHandler.text获取,替代原WWW的w.text
如果你的需求确实是调用登录接口,修正后的GET请求代码如下(注意参数拼接和语法):
public IEnumerator CO_Login(string u, string p, Action<LoginResponse> response) { // 正确拼接GET参数,用&分隔,注意编码特殊字符(如果需要) string url = $"http://localhost:8080/webServicePlataformaDigital/Login.php?alias={u}&password={p}"; using (UnityWebRequest web = UnityWebRequest.Get(url)) { yield return web.SendWebRequest(); if (web.result != UnityWebRequest.Result.Success) { Debug.LogError($"登录请求失败: {web.error}"); response?.Invoke(null); yield break; } Debug.Log(web.downloadHandler.text); LoginResponse result = JsonUtility.FromJson<LoginResponse>(web.downloadHandler.text); response?.Invoke(result); } }
注意:如果参数包含特殊字符(比如空格、@、&等),建议用
UnityWebRequest.EscapeURL()对参数值进行编码,避免请求出错。
内容的提问来源于stack exchange,提问作者Lisbeth Aguirre
相关产品推荐
相关产品推荐

