unity-game-engineasynchronousloadingscene

Loading scene asynchronously in Unity3D not working


So I've done some research about how loading scenes asynchronously works on unity. So far I've found two ways of doing that are very similar and that are based in the same principle.

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

However this doesn't seem to work for me. I still get tons of loading time and the scene shows immediately even if I haven't called the code to show it. I have also tried doing

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

So here is my class in charge of doing this job. I excuse myself if I my error is too simple, I'm new with Unity. Thanks.

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
    }
}

Solution

  • Because of the progress while loop, you never trigger the yield when loading. Try put it into async while loop, like

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