Abstract State - BNS-MarkUlrich/MarksMagicToolbox GitHub Wiki
State is an abstract Unity C# class designed to handle state transitions within a game. It provides functionalities for state entry, exit, loading scenes, and moving to the next state.
To use the State class in your Unity project, follow these steps:
- Copy the
State.csfile into your Unity project's scripts directory.
| Property | Description |
|---|---|
OwningGameStateMachine |
Reference to the owning game state machine behaviour. |
OnStateEnter |
Action triggered upon entering the state. |
OnStateExit |
Action triggered upon exiting the state. |
| Method | Description |
|---|---|
InitState() |
Initializes the state and subscribes it to the state machine. |
SetNextState<TState>() |
Sets the next state to transition to based on the provided state type. |
LoadScene(string sceneName) |
Loads the specified scene if it's not already active. |
EnterState() |
Executes code related to entering the state. |
ExitState() |
Executes code related to leaving the state. |
MoveToNextState() |
Triggers the owning state machine to move to the next state. |
This abstract class serves as a foundation for implementing specific states in a game. It manages state transitions, scene loading, and provides hooks for executing custom code upon entering or exiting states.
Let's create a sample implementation of a game state by extending the State class:
using UnityEngine;
public class MainMenuState : State
{
public MainMenuState() { }
public override void EnterState()
{
base.EnterState();
// Additional actions specific to entering the main menu state
Debug.Log("Entered Main Menu State");
}
public override void ExitState()
{
base.ExitState();
// Additional actions specific to exiting the main menu state
Debug.Log("Exited Main Menu State");
}
public void PlayGame()
{
// Perform actions specific to transitioning to the "Playing" state
SetNextState<PlayingState>();
MoveToNextState();
}
}
public class PlayingState : State
{
public PlayingState() { }
public override void EnterState()
{
base.EnterState();
// Additional actions specific to entering the playing state
Debug.Log("Entered Playing State");
}
public override void ExitState()
{
base.ExitState();
// Additional actions specific to exiting the playing state
Debug.Log("Exited Playing State");
}
}Now, let's demonstrate how to use these states in your game: