Strange behaviour on simple loading screen pattern

Hello,

I am trying to load a scene named “GameLoading” which loads the game scene in the background, while updating a progress bar.

Here is my GameLoading script :

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

public class GameLoading : MonoBehaviour
{
    public ProgressBar progressBar;
   
    void Start()
    {
        StartCoroutine(loadSceneAsync());
    }
   
    private IEnumerator loadSceneAsync() {
       
        AsyncOperation loading = SceneManager.LoadSceneAsync(SessionManager.getSceneToLoad());
       
        while(!loading.isDone) {
            progressBar.setValue(loading.progress/0.9f);
            yield return null;
        }
    }

    // Update is called once per frame
    void Update()
    {

    }
}

And here is how I load the GameLoading scene from another scene :

private static void beginNewExerciseSession() {
        SceneManager.LoadScene("GameLoading");
}

But it’s not working.
When the LoadScene() is called, it freezes Unity for ages before it actually loads the GameLoading. And when GameLoading is finally loaded, it stays for a milisecond before going on to the final game scene, so I’m pretty sure the final scene has already been loaded when GameLoading is displayed.

What seems to happen is that LoadScene() is waiting for the couroutine started in GameLoading to end, before actually loading GameLoading. So nothing happens at expected…

I’m pretty sure I’m doing something wrong, but I find this as a stranged behaviour.

Thank you ! Anselme.

Have you tested in an actual build? I seem to recall there was some slight difference of behavior with async scene load progress when just running in editor… perhaps someone else here can comment on that?

Hi !

Thank you, you are right during the build it loads the loading scene instantly.
But I still have some problems. The progress bar is never updated, it just waits and after 1 or 2 seconds the game scene is loaded.

I noticed that puting a slight delay (0.1s) at the start of the coroutine solves the problem.
Which also actually solves the problem that I had in the editor…

Maybe the problem is calling LoadSceneAsync too soon after calling LoadScene, maybe…

Any other idea ?

Ok, solved !

Actually it was coming from a null reference error, “progressBar” that was still “null” at the moment of the coroutine, so I guess it broke the coroutine and exited it so nothing was happening. Just a quesiton of order of scripts I guess.

Now everything is ok.