- Home /
Why is it not supported to unload the firstly loaded scene?
Why is it not supported to unload the firstly loaded scene?
You basically get this error message if you try (and then the scene does not unload):
Unloading the last scene Assets/Scenes/Game/World 1 - Garden/W1_FirstKey.unity(index: 4), is not supported. Please use SceneManager.LoadScene()/EditorSceneManager.OpenScene() to switch to another scene.
Answer by Lariosss · Mar 28, 2020 at 05:50 PM
For anyone still looking the answer for this.
You have to set the new scene as "Active", before unloading the previous one.
SceneManager.LoadScene("Untitled", LoadSceneMode.Single);
SceneManager.SetActiveScene(SceneManager.GetSceneByName("Untitled"));
SceneManager.UnloadSceneAsync("SampleScene");
Answer by dedemonn · Jan 04, 2021 at 10:17 PM
Encountered this problem in my unit tests, where for each test I was recreating a fresh scene. Basically solution was as Bunny83 said (which I missed and solved it 2h later :D).
public static IEnumerator CreateScene() {
var previousScene = SceneManager.GetSceneByName("Game");
if (previousScene.IsValid()) {
yield return SceneManager.UnloadSceneAsync(previousScene);
}
SceneManager.LoadScene("Scenes/Game", LoadSceneMode.Additive);
var scene = SceneManager.GetSceneByName("Game");
while (!scene.isLoaded) {
yield return new WaitForSeconds(0.1f);
}
}
Answer by Bunny83 · Dec 21, 2015 at 11:15 PM
I still haven't Unity 5.3 but the error says something else than what you said in your title:
Unloading the last scene XXX is not supported
That means you only have one scene loaded at that moment. Unloading that scene would mean you literally destroy everything in your scene.
Unloading a scene only makes sense when you first load another scene additively. Usually when you call SceneManager.LoadScene you load the scene in single mode. So the previous scene would be unloaded automatically when the new scene is loaded.
Answer by RocketFriday · Mar 05, 2021 at 11:24 PM
Similarly to Lariosss's answer because this did fix the error, however not at first because for anyone using the SceneManager.onsceneloaded event it turns out the event passes the loading screen scene a few times before sending the scene ACTUALLY PASSED IN lol So you gotta make sure the scene exists, before following Lariosss's answer.
Like dis:
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
try
{
if (scene == SceneManager.GetSceneAt(1))
{
print("Level Loaded...");
}
}
catch (System.IndexOutOfRangeException s) { return; }
StartCoroutine("SwitchActive"); // <--- using Lariosss's answer
}