GameStateMachine - BNS-MarkUlrich/MarksMagicToolbox GitHub Wiki

Overview

GameStateMachine is a static class in Unity C# designed to manage the states within a game. It facilitates state transitions, state subscriptions, and state checks for game management.

Installation

To use GameStateMachine in your Unity project, follow these steps:

  1. Copy the GameStateMachine.cs file into your Unity project's scripts directory.

Usage

Properties

Property Description
OwningGameStateMachine Reference to the owning game state machine behaviour.
States List of available states within the game state machine.
CurrentState The currently active state within the state machine.

Methods

Method Description
Subscribe(this State state) Allows states to subscribe themselves to the state machine.
InitStateMachine(...) Initializes the state machine behaviour script.
SetState(State newState) Sets the current state to the provided state.
MoveToNextState() Moves the current state to the next state as defined.
CurrentStateIs<TState>() Checks if the current state matches the provided state type.
CurrentStateIs(State state) Checks if the current state matches the provided state instance.
GetState<TState>() Retrieves the reference of a specified state within the machine.
SetState<TState>() Sets the current state to the specified state type.
WinGame() Triggers the win game action from the WaveState.
LoseGame() Triggers the lose game action from the WaveState.

This class enables state management within a game, allowing transitions between states, state checks, and triggering specific actions based on state changes.

Usage Example

Let's create a sample implementation of a game state by extending the State class:


Now, let's demonstrate how to use these states in your game:

using UnityEngine;

public class GameStateManager : MonoBehaviour
{
    private void Start()
    {
        // Set initial state
        GameStateMachine.SetState<MainMenuState>();

        // Perform actions based on the current state
        if (GameStateMachine.CurrentStateIs<MainMenuState>())
        {
            MainMenuState mainMenu = (MainMenuState)GameStateMachine.CurrentState;
            mainMenu.PlayGame(); // Transition to the playing state
        }
    }
}

Repository

[Coming soon]

⚠️ **GitHub.com Fallback** ⚠️