Hello, I’m trying to implement a FSM pattern that would allow me to manage game state (and other states in the future). I find my current implementation wrong, because i have to store in a bool if a game is paused or not to allow me to use the same input for pausing and unpausing the game. Is this the correct way to approach this situation or not?
The current code is working as expected for now.
Code for GameManager object:
using UnityEngine;
public class GameManager : MonoBehaviour
{
private StateMachine stateMachine = new StateMachine();
private IState pauseState = new PauseState();
private IState playState = new PlayState();
private bool isPaused = false;
private void Awake()
{
stateMachine.ChangeState(playState);
}
private void Update()
{
stateMachine.Tick();
}
private void OnEnable()
{
InputReader.Instance.PauseEvent += HandlePause;
}
private void OnDisable()
{
InputReader.Instance.PauseEvent -= HandlePause;
}
void HandlePause()
{
if (isPaused) stateMachine.ChangeState(playState);
else stateMachine.ChangeState(pauseState);
isPaused = !isPaused;
}
}
For FSM:
public class StateMachine
{
private IState currentState;
public void ChangeState(IState newState)
{
if (currentState != null) currentState.Exit();
currentState = newState;
currentState.Enter();
}
public void Tick()
{
if (currentState != null) currentState.Execute();
}
}
For states:
using UnityEngine;
public class PauseState : IState
{
public void Enter()
{
Debug.Log("Game Paused");
}
public void Execute()
{
Debug.Log("Is Paused");
}
public void Exit()
{
Debug.Log("Exiting Paused State");
}
}
using UnityEngine;
public class PlayState : IState
{
public void Enter()
{
Debug.Log("Game Played");
}
public void Execute()
{
Debug.Log("Is Playing");
}
public void Exit()
{
Debug.Log("Exiting Playing State");
}
}