c# - 在后台加载新场景

标签 c# unity3d

我正在创建一个针对 Samsung Gear VR 的 Unity 应用程序。我目前有两个场景:

  1. 初始场景
  2. 第二个场景,数据量大(场景加载时间过长)。

从第一个场景开始,我想在后台加载第二个场景,加载完成后切换到第二个场景。当新场景在后台加载时,用户应保持移动头部以查看 VR 环境的任何部分的能力。

我正在使用 SceneManager.LoadSceneAsync 但它不工作:

// ...

StartCoroutiune(loadScene());

// ...

IEnumerator loadScene(){
        AsyncOperation async = SceneManager.LoadAsyncScene("Scene", LoadSceneMode.Single);
        async.allowSceneActivation = false;
        while(async.progress < 0.9f){
              progressText.text = async.progress+"";
        }
       while(!async.isDone){
              yield return null;
        }
        async.allowSceneActivation = true;
}

使用该代码,场景永远不会改变。

我已经尝试过这种典型的 SceneManager.LoadScene("name"),在这种情况下,场景会在 30 秒后正确更改。

最佳答案

这应该可行

    while(async.progress < 0.9f){
          progressText.text = async.progress.ToString();
          yield return null;
    }

其次,我见过 isDone 永远不会设置为 true 的情况,除非场景已激活。删除这些行:

    while(!async.isDone){
          yield return null;
    }

最重要的是,您将代码锁定在第一个 while 循环中。添加 yield 以便应用程序可以继续加载您的代码。

所以你的整个代码看起来像这样:

IEnumerator loadScene(){
    AsyncOperation async = SceneManager.LoadAsyncScene("Scene", LoadSceneMode.Single);
    async.allowSceneActivation = false;
    while(async.progress <= 0.89f){
          progressText.text = async.progress.ToString();
          yield return null;
    }
    async.allowSceneActivation = true;
}

尽管如此,您问题的最大罪魁祸首是第一个 while 循环中的锁定。

关于c# - 在后台加载新场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40014574/

相关文章:

c# - 选择并合并一系列单元格

c# - C#Unity和C服务器中的TcpClient

c# - 从另一个脚本获取变量的最佳方法

unity3d - Unity 'Agents' 选项卡和 'Bake' 选项卡中代理的配置有什么区别?

c# - EF Core SingleOrDefaultAsync 编译时返回类型错误

c# - 单击 ComboBoxItem 问题事件后,WPF 将 ComboBox 设置为 -1 索引

c# - 来自代码的带有样式和 DateTriggers 的 DataTemplate

c# - Automapper DynamicMap 随机无法映射匿名类型

c# - 用鼠标拖动对象并将其捕捉到值

c# - 来自过滤器代码的音频点击/弹出