using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; /// /// SystemController singleton /// public class SystemController { /// /// The instance controlling the singleton /// private static SystemController instance = null; /// /// Stack of the loaded scenes, used to easily go back to previous scenes /// private Stack sceneStack = new Stack(); /// /// Index of the previous loaded scene /// public int previousScene = -1; /// /// Index of the current loaded scene /// public int currentScene = -1; /// /// Get the instance loaded by the singleton /// /// SystemController instance public static SystemController GetInstance() { // Create a new instance if non exists if (instance == null) { instance = new SystemController(); instance.currentScene = SceneManager.GetActiveScene().buildIndex; instance.sceneStack.Push(instance.currentScene); } return instance; } /// /// Get the number of passively 'active' scenes /// public int GetSceneStackSize() { return sceneStack.Count; } /// /// Load the scene and push on the stack /// /// Path of the scene public void LoadNextScene(string scenePath) { LoadNextScene(SystemController.GetSceneIndex(scenePath)); } /// /// Get the index of a given scene /// /// Path of the scene /// public static int GetSceneIndex(string scenePath) { return SceneUtility.GetBuildIndexByScenePath(scenePath); } /// /// Load the scene and push on the stack /// /// Buildindex of the scene public void LoadNextScene(int sceneIndex) { previousScene = currentScene; currentScene = sceneIndex; sceneStack.Push(currentScene); SceneManager.LoadScene(currentScene); } /// /// Swap the current scene with the new scene on the stack /// /// Path of the scene public void SwapScene(string scenePath) { SwapScene(SystemController.GetSceneIndex(scenePath)); } /// /// Swap the current scene with the new scene on the stack /// /// Buildindex of the scene public void SwapScene(int sceneIndex) { currentScene = sceneStack.Pop(); LoadNextScene(sceneIndex); } /// /// Go back to the previous scene and unload the current scene /// public void BackToPreviousScene() { previousScene = sceneStack.Pop(); if (sceneStack.Count > 0) SceneManager.LoadScene(currentScene = sceneStack.Peek()); else Application.Quit(); } /// /// Go back to a specific scene, unloading all the scenes on the way /// /// Path of the scene public void BackToScene(string scenePath) { BackToScene(SystemController.GetSceneIndex(scenePath)); } /// /// Go back to a specific scene, unloading all the scene on the way /// /// Buildindex of the scene public void BackToScene(int sceneIndex) { previousScene = currentScene; while (0 < sceneStack.Count && sceneStack.Peek() != sceneIndex) sceneStack.Pop(); if (sceneStack.Count > 0) SceneManager.LoadScene(currentScene = sceneStack.Peek()); else Application.Quit(); } }