- Home /
Code not executed after LoadSceneAsync in a Coroutine
I'm relatively new to Coroutines and Level Loading, so please forgive my presumably rookie mistake.
I'm calling the following function using StartCoroutine:
public IEnumerator LoadLevel(string levelPath)
{
AsyncOperation loadOp = SceneManager.LoadSceneAsync(levelPath);
while (!loadOp.isDone)
{
print("loading...");
yield return null;
}
print("loaded level");
}
The level loads, "loading..." is printed once, but the second print never occurs. What have I missed here, or not understood? I thought execution would carry on after the while loop was exited?
Thanks for the assistance!
Answer by Bunny83 · Nov 07, 2017 at 05:01 PM
Once the new scene is loaded and activated the old scene is destroyed at the same time. That means unless you have used DontDestroyOnLoad, the object that runs the coroutine will also be destroyed. This will terminate the coroutine as well.
So there are basically two ways:
Run your coroutine on a top level gameobject in the old scene and use DontDestroyOnLoad on that gameobject in order to make it "survive" the level load.
Another way would be to set allowSceneActivation to false. However in this case you can't wait for "isDone" to turn true as this will never happen as you can read in the documenation. Instead you should check the progress if it reached "0.9". Now you can do some actions before the actual scene switch. However when you set it back to true and the actual level switch happens your old object will be destroyed and the coroutine is gone.
It depends on what you actually want to do.
Thanks, yeah, it's been set up on a game object that's set to be kept after a level load; and the gameobject is still there in the scene after loading is complete; which is why I'm perplexed as to why it's not continuing...!
Tried different variations of this with no luck:
public IEnumerator LoadLevel(string levelPath)
{
AsyncOperation loadOp = Scene$$anonymous$$anager.LoadSceneAsync(levelPath);
loadOp.allowSceneActivation = false;
while (loadOp.progress < 0.9f)
{
print("loading..." + loadOp.progress);
yield return null;
}
print("mostly loaded level");
loadOp.allowSceneActivation = true;
}
Never reaches "mostly loaded level" print, and therefore never activates the scene either. Same issue as using .isDone...
Do Coroutines get killed when a level is loaded?!