在背景中加载新场景

adr*_*992 4 c# unity-game-engine unity5

我正在创建一个针对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;
}
Run Code Online (Sandbox Code Playgroud)

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

我试过这个典型SceneManager.LoadScene("name")的情况,在这种情况下,场景在30秒后正确变化.

Ria*_*ers 7

这应该工作

    while(async.progress < 0.9f){
          progressText.text = async.progress.ToString();
          yield return null;
    }
Run Code Online (Sandbox Code Playgroud)

其次,isDone除非场景已激活,否则我已经看到永远不会设置为true的情况.删除这些行:

    while(!async.isDone){
          yield return null;
    }
Run Code Online (Sandbox Code Playgroud)

最重要的是,您将在第一个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;
}
Run Code Online (Sandbox Code Playgroud)

然而,你问题的最大罪魁祸首是锁定第一个while循环.

  • 你覆盖了所有可能的问题,但在这种情况下,场景无法加载的问题仅仅是因为`async.isDone`.应该删除`async.isDone`.你对`yield return null`语句是正确的,但这与浮点比较没有关系. (3认同)
  • @ParadoxForge我理解你想说的是什么,但这不适用于此.完成加载后,`async.progress`将始终返回'0.9`的确切值.完成加载后,它不会**返回任何其他值.甚至可以安全地做`if(async.progress == 0.9f){async.allowSceneActivation = true;}`你可以在这里阅读更多相关信息(http://www.alanzucconi.com/2016/) 3月30日/加载栏功能于统一/).至于你的`0.89`,这可能会引起问题,因为你将激活一个尚未加载100%的场景.你的其余答案都很好. (2认同)
  • 别客气.还有一件事.当[allowSceneActivation]设置为"false"时,此[仅](https://docs.unity3d.com/550/Documentation/ScriptReference/AsyncOperation-allowSceneActivation.html)适用.在这种情况下,OP在开头设置为"false". (2认同)