Search Unity

Switch between multiple scenes

Discussion in 'Editor & General Support' started by pedreror1, Mar 23, 2020.

  1. pedreror1

    pedreror1

    Joined:
    Mar 16, 2014
    Posts:
    3
    HI all,
    Im creating a system to be able to switch between scenes, the Idea is to load all scenes on startup but leave them unactive, then when the time comes activate the next scene and unload the previous one.

    the problem is I cannot unload any scene unless I activate them all, Im guesing it has to do with the asyncOperation stack.

    here is my code for loading all the scenes

    Code (CSharp):
    1.  
    2.  void Start()
    3.     {
    4.          
    5.  
    6.          StartCoroutine(loadScenes());
    7.     }
    8.     public IEnumerator loadScenes()
    9.     {
    10.         yield return new WaitForSeconds(0.03f);
    11.         for (int sceneToLoadIndex = 1; sceneToLoadIndex < SceneManager.sceneCountInBuildSettings; sceneToLoadIndex++)
    12.         {
    13.             if (!LevelList.ContainsKey(sceneToLoadIndex))
    14.                 yield return StartCoroutine(LoadScene2(sceneToLoadIndex));
    15.         }
    16.  
    17.         currentScene = 0;
    18.     }
    19.  
    20.  
    this is the Unloading logic
    Code (CSharp):
    1.  
    2.   private IEnumerator UnLoadScene(int sceneToUnload)
    3.     {
    4.  
    5.         yield return null;
    6.  
    7.  
    8.         Scene scene = SceneManager.GetSceneAt(sceneToUnload);
    9.        
    10.       SceneManager.UnloadSceneAsync(scene);
    11.  
    12.        
    13.     }
    14.  
    and here is my code for changing between scenes
    Code (CSharp):
    1.  
    2.  public IEnumerator setNewSceneActive(int newActiveSceneIndex, bool unloadPreviousScene)
    3.     {
    4.  
    5.         if (unloadPreviousScene)
    6.         {
    7.             yield return StartCoroutine(UnLoadScene(lastScene));
    8.         }
    9.         else
    10.             yield return null;
    11.  
    12.  
    13.         if (LevelList[newActiveSceneIndex] != null && (LevelList[newActiveSceneIndex].progress >= 0.9f))
    14.         {
    15.  
    16.             LevelList[newActiveSceneIndex].allowSceneActivation = true;  }
    17.        
    18.     }
    19.  


    I know I could use an empty inactive Gameobject as a root for each scene and deactivate/destroy it when changing scene but I think there must be a way to achieve this using only the unity sceneManagment system

    cheers