LoadLevel*Aynsc() and Coroutine

I have a LoadScene() method within my script which looks like this,

void LoadScene(String scene)
{
    async = Application.LoadLevelAdditiveAsync(scene);
    StartCoroutine(SceneLoadCallback(scene));
}

where ‘async’ is declared as follows,

private static AsyncOperation async = null;

The Coroutine ‘SceneLoadCallBack()’ is defined as follows,

IEnumerator SceneLoadCallback(String scene)
{
	while (!async.isDone) {
		Debug.Log("Checkpoint-1")
		yield return null;
		Debug.Log("Checkpoint-2")
	}
	
	yield break;
	Debug.Log("Checkpoint-3")
}

The method ‘LoadScene()’ is called directly from the ‘Update()’ method of my script. The level that I am trying to load gets loaded correctly, however ‘Checkpoint-2’ and ‘Checkpoint-3’ never get printed.

I am new to Unity and have just learned how to use Coroutines. If I understand it right, ‘yield return null’ should cause Coroutine body to resume executing (after Update() is called) at where it left. But that doesn’t seems to be happening. Any insights here would be helpful.

You should run the method ‘LoadScene()’ from ‘Start()’ and not from ‘Update()’.

Coroutines do not need to be in ‘Update’ in order to run.

We experienced a similar issue whith LoadLevelAsync. It seems the isDone property does not work as expected and is never set to true (unless it has been fixed in recent releases). Instead we used the progress property and checked when it was over 0.91f. I know it’s not a very ellegant solution, but it works.

Another approach you might want to try is to set the allowSceneActivation to false after calling LoadLevelAsync, then do whatever you want to do while the scene is loading, and set allowSceneActivation back to true when you have finished. That way you don’t need to control when the scene has finished loading because it will automatically load when it’s ready.

Finally, yield break, breaks the flow of the coroutine, which means that anything after that line will never get executed.

“AsyncOperation.isDone will never be
true if
AsyncOperation.allowSceneActivation is
false. Progress will stop at around
0.9f.”

Check this answer: https://answers.unity.com/answers/956839/view.html