Loading and Unloading scenes
I have one scene that I will like to unload (Scene A) when I click a button. I do not want the scene to be deleted because I want to save the data. I basically want the scene to disable. Once it's disable, I have another scene that will load addictive (Scene B) and will be the active scene in the game. I then want to reverse this by removing Scene B and enable Scene A then set Scene A as the active scene. I tried to do this with SceneManager, but I had no success. It will load Scene B, but it will not disable/unload Scene A?
public void loadHelpScene(string id)
{
SceneManager.LoadScene(id, LoadSceneMode.Additive);
if (SceneManager.UnloadScene(sceneName))
print("Success");
}
SceneName is the current scene loaded and id is the scene to be loaded additive.
Answer by VindictPL · Feb 15, 2017 at 02:49 PM
You can load scene B additive, set it as active scene and disable all root GameObjects in scene A. When you want to get back to scene A just enable them, set scene A as active and unload scene B
To disabe:
foreach(GameObject g in SceneManager.GetActiveScene().GetRootGameObjects()){
g.SetActive (false);
}
To enable:
foreach(GameObject g in SceneManager.GetSceneByName("A").GetRootGameObjects()){
g.SetActive (true);
}
Hi, i have the same problem as OP, This code works disabling and enabling the scenes, but why does it double the next loaded scene?
Answer by LibertyCoding · Aug 23, 2018 at 05:04 PM
You're doing LoadScene as additive. Which will load another. You will need to Iterate over the loaded scenes or by name and check if it is already loaded and inactive and then enable all root objects on that scene instead of loading it again.
Something like this:
private void SetGameObjectsActive(GameObject[] objects, bool active)
{
for (int i = 0; i < objects.Length; i++)
{
objects[i].gameObject.SetActive(active);
}
}
public void loadHelpScne(string id)
{
bool foundScene = false;
for (int sceneIndex = 0; sceneIndex < SceneManager.sceneCount; sceneIndex++)
{
var scene = SceneManager.GetSceneAt(sceneIndex);
if (!scene.IsValid()) continue;
if (scene.name.Equals(id))
{
SetGameObjectsActive(scene.GetRootGameObjects(), false);
}
else if (scene.name.Equals(sceneName))
{
SetGameObjectsActive(scene.GetRootGameObjects(), true);
foundScene = true;
}
}
if (!foundScene)
{
SceneManager.LoadScene(id, LoadSceneMode.Additive);
}
sceneName = id;
}