You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity嵌套协程中while循环无法返回下载进度数据求助

解决Unity AssetBundle下载进度实时更新问题

你的问题核心在于DownloadAssetBundle协程的执行逻辑错误:当你执行yield return request.SendWebRequest()时,协程会直接阻塞到整个下载完成才继续运行,导致后面的while(!request.isDone)循环完全不会触发。

修改后的DownloadAssetBundle协程代码

IEnumerator DownloadAssetBundle(string localLocation, string remoteLocation, string niceText)
{
    // 直接更新当前下载项文本,赋值操作无需yield return
    CurrentItemText.text = niceText;

    using (var cert = new ForceAcceptAll())
    using (UnityWebRequest request = new UnityWebRequest(remoteLocation, UnityWebRequest.kHttpVerbGET))
    {
        request.certificateHandler = cert;
        request.downloadHandler = new DownloadHandlerFile(localLocation);

        // 发送请求但不等待完成,让协程继续执行进度循环
        request.SendWebRequest();

        // 下载过程中每帧更新进度
        while (!request.isDone)
        {
            // 修正进度值范围,避免初始阶段的异常数值
            float progress = Mathf.Clamp01(request.downloadProgress);
            string progressText = $"{progress * 100:F1}%";
            
            Debug.Log(progressText);
            ProgressText.text = progressText;

            // 等待下一帧再检查进度,实现实时更新
            yield return null;
        }

        // 下载完成后检查请求状态
        if (request.result != UnityWebRequest.Result.Success)
        {
            Debug.LogError($"下载失败: {request.error}");
        }
    }
}

关键改动说明

  • 移除阻塞式的yield return request.SendWebRequest():改为仅调用request.SendWebRequest(),让协程能进入后续的进度循环逻辑。
  • 用using管理资源:自动释放ForceAcceptAll和UnityWebRequest,避免内存泄漏。
  • 修复进度值异常:通过Mathf.Clamp01确保进度值始终在0-1区间,避免显示负数或超过100%的异常数值。
  • 替换错误的yield return对象:yield return null会让协程暂停到下一帧,保证每帧都能更新进度;原代码中yield return ProgressText是等待该对象销毁,逻辑完全错误。
  • 增加错误检测:下载完成后校验请求结果,方便排查下载失败问题。

额外优化建议

  • Unity 2020及以上版本,建议使用UnityWebRequest.GetAssetBundle()专用API,比手动创建DownloadHandlerFile更简洁高效。
  • 可将进度更新逻辑封装为单独方法,减少重复代码。

内容的提问来源于stack exchange,提问作者1nKy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 09:05:37