This is intended to provide a simple state system for the overall operation of the game levels. Does not apply to the menu screen, is only for "Playing the game" scenes.
Game States
I've included five states, three of which are active during game play. As of this writing nothing actually happens in Preloading, but I've added it just in case. Similarly, the only thing that will happen in "Closing", will be application quit or loading the main menu.
The other states are perhaps self explanatory.
GameState (Events)
The GameState class will send out all of the events, and will be the one class which handles transitioning from one state to another. Here is a selection from the script.
GameState.cs
publicclassGameState:MonoBehaviour{publicstaticGameState gameState;privateLegendEnums.GameState _gameState =LegendEnums.GameState.Preloading; // Always start at preloadingpublicAction<LegendEnums.GameState> OnGameStateEntered;publicLegendEnums.GameState ActiveState {get=> _gameState;set=> _gameState = value; } //===================================================================================== // CYCLE METHODS //=====================================================================================privatevoidAwake() {if (gameState ==null) gameState =this;elseif (gameState !=this)Destroy(gameObject);SetGameState(LegendEnums.GameState.Preloading); // Start with this }privatevoidUpdate() {DoPreloading();DoLoading();DoGameOn();DoSaving();DoClosing(); } //===================================================================================== // SET METHODS //=====================================================================================publicvoidSetGameState(LegendEnums.GameState newGameState) { ActiveState = newGameState;OnEnterPreloading();OnEnterLoading();OnEnterGame();OnEnterSaving();OnEnterClosing(); }...privatevoidDoGameOn() {if (ActiveState !=LegendEnums.GameState.GameOn) return; // Global actions will go here, things outside of the other classes. }...privatevoidOnEnterPreloading() {if (ActiveState !=LegendEnums.GameState.Preloading) return;OnGameStateEntered?.Invoke(LegendEnums.GameState.Preloading); }...}
LegendMonoBehaviour
Any class which relies on states will be a LegendMonoBehaviour, which is just a MonoBehaviour, which has these methods.
This is from Game.cs, the main "Game" class, which acts as a hub for a lot of the other classes. The AwakeSetup() method is called in Awake(), and comes after the SubscribeToEvents method on LegendMonoBehaviour.
Game.cs
...protectedoverridevoidAwakeSetup(){if (game ==null) {ehaviour game =this;SceneManager.sceneLoaded+= SceneLoaded; }elseif (game !=this) {game._firstLoad=false;Destroy(gameObject); }UnityEngine.Random.InitState(seed); // Random seed for future game option}...