Unity解决:没有UnityWebRequest.Result

当我在Unity 2019中使用Unity 2021的代码satable时。
控制台显示
“UnityWebRequest”不包含“result”的定义,并且找不到接受“UnityWebRequest”类型的第一个参数的可访问扩展方法“result”(是否缺少using指令或程序集引用?)
漏洞/问题:

if (req.result == UnityWebRequest.Result.ConnectionError || req.result == UnityWebRequest.Result.ProtocolError)

版本2020.3中添加了result
在该版本之前,只需遵循相应版本API中的示例,例如2019.4 API
例如,您可以简单地检查error中是否有任何内容

using (var webRequest = UnityWebRequest.Get(uri))
{
    yield return webRequest.SendWebRequest();
    if (!string.IsNullOrWhiteSpace(webRequest.error))
    {
        Debug.LogError($"Error {webRequest.responseCode} - {webRequest.error}");
        yield break;
    }
    Debug.Log(webRequest.downloadHandler.text);
}

或者如果您想进一步区分isNetworkError(包括没有互联网连接、主机不可访问、DNS解析错误等错误)和isHttpError(基本上与responseCode >= 400相同)
如果你的问题是关于向下兼容性,但支持两个版本要么坚持2020.3之前的方式或使用Conditional Compilation和做例如.

#if UNITY_2020_3_OR_NEWER
    if(webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)  
#else
    if(!string.IsNullOrWhiteSpace(webRequest.error))
#endif
    {
        Debug.LogError($"Error {webRequest.responseCode} - {webRequest.error}");
        yield break;
    }

或者如下:

   /// <summary>
    /// 执行下载行为
    /// </summary>
    /// <param name="bundleInfoList"></param>
    /// <returns>返回的List包含的是还未下载的Bundle</returns>
    private async Task<List<BundleInfo>> ExecuteDownload(ModuleConfig moduleConfig, List<BundleInfo> bundleList)
    {
        while (bundleList.Count > 0)
        {
            BundleInfo bundleInfo = bundleList[0];

            UnityWebRequest request = UnityWebRequest.Get(GetServerURL(moduleConfig, bundleInfo.bundle_name));

            string updatePath = GetUpdatePath(moduleConfig.moduleName);

            request.downloadHandler = new DownloadHandlerFile(string.Format("{0}/" + bundleInfo.bundle_name, updatePath));

            await request.SendWebRequest();
            
#if UNITY_2020_3_OR_NEWER

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("下载资源:" + bundleInfo.bundle_name + " 成功");

                bundleList.RemoveAt(0);
            }
            else
            {
                break;
            }

#else
            if (string.IsNullOrEmpty(request.error) == true)
            {
                Debug.Log("下载资源:" + bundleInfo.bundle_name + " 成功");

                bundleList.RemoveAt(0);
            }
            else
            {
                break;
            }
#endif
            

            
        }

        return bundleList;
    }

猜你喜欢

转载自blog.csdn.net/weixin_39114763/article/details/134410097
今日推荐