如何使用Unity的RestClient发起多请求并在全部完成后执行函数?
批量图片下载完成判断实现方案
你可以通过以下两种方案实现批量请求完成的判断,第一种对新手更友好易理解:
方案1:计数器实现(推荐新手使用)
核心逻辑是通过两个变量统计总请求数和已完成请求数,每个请求不管成功失败都计入已完成数量,数量匹配时触发目标函数。
示例代码如下:
using System.Collections.Generic; using System.IO; using Proyecto26; using UnityEngine; public class ImageDownloader : MonoBehaviour { // 提前配置你的图片URL列表 public List<string> imageUrls = new List<string>(); public void StartBatchDownload() { int totalRequests = imageUrls.Count; int completedRequests = 0; foreach (var url in imageUrls) { RestClient.Get(url) .Then(response => { byte[] imageBytes = response.Data; // 生成唯一存储路径,避免文件覆盖 string fileName = Path.GetFileName(url); string savePath = Path.Combine(Application.persistentDataPath, fileName); File.WriteAllBytes(savePath, imageBytes); Debug.Log($"图片 {fileName} 下载成功"); }) .Catch(err => { Debug.LogError($"图片下载失败:{err.Message}"); }) .Finally(() => { // 无论成功失败都计数+1 completedRequests++; if (completedRequests == totalRequests) { // 所有请求执行完毕,调用目标函数 OnAllDownloadFinished(); } }); } } // 所有下载完成后执行的逻辑 private void OnAllDownloadFinished() { Debug.Log("全部图片下载任务已完成"); // 此处写入你要执行的后续逻辑 } }
该方案优势是逻辑简单,即使部分图片下载失败也能正常触发完成回调,不会出现流程卡住的问题。
方案2:Promise.All 实现(更简洁优雅)
你用的RestClient返回的是标准Promise对象,可直接用Promise.All方法等待所有请求完成:
using System.Collections.Generic; using System.IO; using System.Linq; using Proyecto26; using UnityEngine; public class ImageDownloader : MonoBehaviour { public List<string> imageUrls = new List<string>(); public void StartBatchDownload() { // 生成所有请求的Promise集合 var allRequests = imageUrls.Select(url => RestClient.Get(url) .Then(response => { byte[] imageBytes = response.Data; string fileName = Path.GetFileName(url); string savePath = Path.Combine(Application.persistentDataPath, fileName); File.WriteAllBytes(savePath, imageBytes); }) .Catch(err => { Debug.LogError($"图片下载失败:{err.Message}"); // 如果允许部分请求失败仍触发完成回调,需加此行吞掉错误 return Promise.Resolved(); }) ).ToArray(); // 等待所有Promise执行完成 Promise.All(allRequests) .Then(results => { OnAllDownloadFinished(); }) .Catch(err => { // 如果未给单个请求加Catch吞错,任意请求失败都会进入此处 Debug.LogError($"批量下载出现异常:{err.Message}"); }); } private void OnAllDownloadFinished() { Debug.Log("全部图片下载任务已完成"); // 此处写入你要执行的后续逻辑 } }
注意事项
- 存储路径尽量使用Unity提供的标准路径如
Application.persistentDataPath,不要写死绝对路径,避免多平台兼容问题 - 如果下载的图片数量较多,建议做分批请求,避免同时发起大量请求被服务器限流或导致Unity卡顿
- 如果需要统计成功/失败的具体数量,可以额外添加两个计数器分别在
Then和Catch回调中累加即可
内容的提问来源于stack exchange,提问作者hot_barbara
相关产品推荐
相关产品推荐

