【问题标题】:Loading new scene in background在后台加载新场景
【发布时间】:2016-10-13 07:15:15
【问题描述】:

我正在创建一个针对 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 秒后正确更改。

【问题讨论】:

    标签: c# unity3d unity5


    【解决方案1】:

    这应该可以工作

        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 循环中的锁定。

    【讨论】:

    • 您涵盖了所有可能的问题,但在这种情况下,场景无法加载的问题仅仅是因为async.isDoneasync.isDone 应该被删除。您对 yield return null 声明是正确的,但这与浮点比较无关。
    • Unity 在 0.9 时停止加载场景,对吗?我对此有点生疏,但是由于浮点精度,它实际上不可能是 0.899999999,这实际上永远不会满足 where 子句吗?
    • @ParadoxForge 我明白你想说什么,但这不适用于这里。完成加载后,async.progress 将始终返回 0.9 的确切值。完成加载后,它不会返回任何其他值。做if(async.progress == 0.9f){async.allowSceneActivation = true;} 甚至是可以安全的,您可以阅读更多关于此here 的信息。至于您的0.89,这可能会导致问题,因为您将激活尚未 100% 加载的场景。您的其余答案都很好。
    • 感谢@Programmer 的详细说明,我将编辑答案
    • 不客气。还有一件事。当allowSceneActivation 设置为false 时,此only 适用。在这种情况下,它在开头被OP设置为false
    猜你喜欢
    • 1970-01-01
    • 2016-10-12
    • 2021-07-11
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多