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

如何在摘下Quest头显时实现Unity多下载任务顺序完成

Quest头显摘下后多任务顺序下载异常的解决方法

问题场景

使用UnityWebRequest发起单个下载任务时,摘下Quest头显后任务能正常完成,但无法保存文件或启动下一个下载任务。需要实现摘下头显后仍能完成多任务顺序下载,可通过保持头显唤醒或让脚本在头显关闭后继续运行两种方向解决。


解决方案

方案一:阻止头显休眠

Quest默认摘下后会进入休眠状态,可通过Unity API强制保持设备唤醒:

  • 在下载任务启动前,设置Screen.sleepTimeout = SleepTimeout.NeverSleep;,阻止系统休眠
  • 全部下载完成后,恢复默认设置:Screen.sleepTimeout = SleepTimeout.SystemSetting;

方案二:允许应用后台运行

Quest摘下头显后,Unity应用默认会暂停,需修改项目设置让应用在后台持续运行:

  1. 打开Unity编辑器的Edit > Project Settings > Player
  2. 切换到Android标签,找到Resolution and Presentation模块,勾选Run In Background
  3. 在代码中启动下载前,主动设置Application.runInBackground = true;,确保后台运行生效

修改后的完整下载代码

using UnityEngine;
using System.Collections;
using System.IO;

public class VideoDownloader : MonoBehaviour
{
    public VideoData[] videos;
    public int numberOfMissingVids;
    public int numberOfVideos;
    public UnityEngine.UI.Text downloadStatusText;
    public UnityEngine.UI.Image imageIndicator;

    IEnumerator DownloadAllVideosSequentially()
    {
        // 开启后台运行并阻止设备休眠
        Application.runInBackground = true;
        Screen.sleepTimeout = SleepTimeout.NeverSleep;

        int totalMissing = numberOfMissingVids;
        int missingCounter = 1;
        for (int i = 0; i < numberOfVideos; i++)
        {
            if (!videos[i].Downloaded)
            {
                Debug.Log($"正在下载 {videos[i].FileName} 从 {videos[i].OnlinePath}");
                downloadStatusText.text = $"正在下载文件 {missingCounter}/{totalMissing}... 0%";
                yield return StartCoroutine(DownloadVideo(videos[i]));
                missingCounter++;
            }
        }

        // 下载完成后恢复系统默认设置
        Screen.sleepTimeout = SleepTimeout.SystemSetting;
        Application.runInBackground = false;
        downloadStatusText.text = "所有文件下载完成!";
    }

    IEnumerator DownloadVideo(VideoData video)
    {
        // 使用using自动释放UnityWebRequest资源
        using (UnityWebRequest uwr = UnityWebRequest.Get(video.OnlinePath))
        {
            uwr.SendWebRequest();

            while (!uwr.isDone)
            {
                float progress = Mathf.Clamp01(uwr.downloadProgress);
                imageIndicator.fillAmount = progress;
                // 优化进度更新逻辑,避免原字符串截取的潜在bug
                downloadStatusText.text = $"正在下载文件 {missingCounter}/{totalMissing}... {(int)(progress * 100)}%";
                yield return null;
            }

            if (uwr.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("下载错误: " + uwr.error);
                downloadStatusText.text = $"下载失败: {video.FileName}";
            }
            else
            {
                string savePath = Path.Combine(Application.persistentDataPath, video.FileName);
                downloadStatusText.text = $"正在保存 {video.FileName}";
                // 确保保存目录存在,避免路径错误导致保存失败
                Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                File.WriteAllBytes(savePath, uwr.downloadHandler.data);
                
                numberOfMissingVids--;
                Debug.Log($"{video.FileName} 已保存至 {savePath}");
                video.SetFinalPath(savePath);
                video.SetDownloaded(true);
            }
        }
    }
}

// 配套的VideoData数据类
public class VideoData
{
    public string FileName;
    public string OnlinePath;
    private bool _downloaded;
    private string _finalPath;

    public bool Downloaded => _downloaded;

    public void SetDownloaded(bool value)
    {
        _downloaded = value;
    }

    public void SetFinalPath(string path)
    {
        _finalPath = path;
    }
}

代码关键调整说明

  1. 新增后台运行与休眠阻止逻辑,确保头显摘下后应用不暂停、设备不休眠
  2. 使用using语句自动管理UnityWebRequest资源,替代手动Dispose
  3. 优化进度文本更新逻辑,避免原代码中字符串截取的潜在错误
  4. 添加目录创建逻辑,防止保存路径不存在导致的文件保存失败
  5. 下载完成后恢复系统默认设置,避免影响设备正常功耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:04:54