Unity UnityWebRequest增加重试

逻辑比较简单,直接上代码:

        IEnumerator Request(string url, string method, Dictionary<string, string> headers, byte[] bodyRaw, int retryCount, System.Action<DownloadHandler> callback)
        {
            for (int i = 0; i < retryCount; i++)
            {
                using (UnityWebRequest request = new UnityWebRequest(url, method))
                {
                    if (headers != null)
                    {
                        foreach (var head in headers)
                        {
                            request.SetRequestHeader(head.Key, head.Value);
                        }
                    }
                    request.uploadHandler = new UploadHandlerRaw(bodyRaw);
                    request.downloadHandler = new DownloadHandlerBuffer();
                    request.timeout = 60;
                    yield return request.SendWebRequest();
                    if (request.result != UnityWebRequest.Result.Success)
                    {
                        yield return new WaitForSeconds(3f);
                    }
                    else
                    {
                        callback?.Invoke(request.downloadHandler);
                        yield break; //终止迭代器函数的执行,并返回到迭代器函数的调用点
                    }
                }
            }
        }

  

将UnityWebRequest改成异步,看我这篇文章:https://www.cnblogs.com/Jason-c/p/17596714.html

posted on 2024-01-15 11:23  Jason_c  阅读(164)  评论(0编辑  收藏  举报