在Unity3D中异步加载场景无法正常工作

时间:2019-04-03 03:28:03

标签: unity3d asynchronous loading scene

因此,我已经完成了一些有关如何异步加载场景以统一工作的研究。到目前为止,我发现了两种非常相似且基于相同原理的方式。

   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);

这是我班上负责这项工作的。如果我的错误太简单了,请原谅。我是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
    }
}

1 个答案:

答案 0 :(得分:1)

由于while循环的进度,您在加载时永远不会触发收益。 尝试将其放入异步while循环,例如

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

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

}