在 Unity3D 中异步加载场景不起作用

Loading scene asynchronously in Unity3D not working

所以我研究了如何在 unity 上异步加载场景。到目前为止,我发现有两种非常相似的方法,并且基于相同的原理。

   StartCoroutiune(loadScene());

    private AsyncOperation async;

     // ...

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

    }

    public void showScene(){
     async.allowSceneActivation = true;
    }

然而这似乎对我不起作用。即使我没有调用代码来显示它,我仍然需要大量的加载时间并且场景会立即显示。我也试过

SceneManager.LoadAsyncScene("Scene", LoadSceneMode.Additive);

所以我 class 负责这项工作。如果我的错误太简单,请原谅我,我是 Unity 的新手。谢谢

using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager_StartGame : MonoBehaviour
{
    private GameManager_MasterMenu gameManagerRef;
    private AsyncOperation loadGame;

    private void OnEnable()
    {
        SetInitialReferences();
        StartCoroutine("loadMainScene");//loads scene before the game starts
        gameManagerRef.ContinueGameEvent += StartGame; //subscribing the StartGame method to an Event
    }

    private void OnDisable()
    {
       gameManagerRef.ContinueGameEvent -= StartGame;//getting the references to the game Manager
    }

    void SetInitialReferences()
    {
        gameManagerRef = GetComponent<GameManager_MasterMenu>();
    }

    IEnumerator loadMainScene()
    {
        Debug.LogWarning("ASYNC LOAD STARTED - " +
        "DO NOT EXIT PLAY MODE UNTIL SCENE LOADS... UNITY WILL CRASH");
        loadGame = SceneManager.LoadSceneAsync(1,LoadSceneMode.Single);
        loadGame.allowSceneActivation = false;//setting the allowscene to false so that it won't show it immediately
        yield return loadGame;
    }


    void StartGame()
    {
        if (GameReferences.currentSave == null)
        {
            GameReferences.currentSave = GameReferences.dBConnector.GetLastSave();
        }
        loadGame.allowSceneActivation = true; //is activated from the outside
    }
}

由于while循环的progress,加载时永远不会触发yield。 尝试将其放入异步 while 循环中,例如

IEnumerator loadScene(){
      async = SceneManager.LoadAsyncScene("Scene", LoadSceneMode.Single);
      async.allowSceneActivation = false;

      while(!async.isDone){
              progressText.text = async.progress+"";
              yield return null;
      }

}
using UnityEngine.SceneManagement;
   
SceneManager.LoadScene(1, LoadSceneMode.Single);

//SceneManager.LoadSceneAsync - (Loads the Scene asynchronously in the background.)
//1 - (BuildIndex or "my scene" StringName.)
//LoadSceneMode.Additive - (Adds the Scene to the current loaded Scenes.)
//LoadSceneMode.Single - (Closes all current loaded Scenes and loads a Scene.)