Skip to content

State Manager

Valk edited this page Dec 19, 2024 · 4 revisions

Important

I have recently discovered the power of composition over inheritance. In light of this, the state manager you see below may change in the near future.

The state manager employs functions as states instead of using classes for state management. The State class is provided in the GodotUtils submodule. Below an example is provided to illustrate this approach.

Create a new file named Player.cs and add the following script to it.

public partial class Player : Entity // This script extends from Entity but it may extend from CharacterBody3D for you
{
    State curState;

    public override void _Ready()
    {
        curState = Idle();
        curState.Enter();
    }

    public override void _PhysicsProcess(double delta)
    {
        curState.Update(delta);
    }

    public void SwitchState(State newState)
    {
        curState.Exit();
        newState.Enter();
        curState = newState;

        GD.Print($"Switched to {newState}"); // Useful for debugging
    }
}

Create another file named PlayerIdle.cs and add the following.

public partial class Player
{
    private State Idle()
    {
        State state = new(nameof(Idle))
        {
            Enter = () =>
            {
                // What happens on entering the idle state?
            },

            Update = delta =>
            {
                // What happens on every frame in the idle state?
            },

            Exit = () =>
            {
                // What happens on exiting the idle state?
            }
        };

        return state;
    }
}

Do a similar process when adding new states.

Note

States have been greatly simplified with the new EnemyComponent script. Check out res://Genres/2D Top Down/Scenes/Prefabs/frog.tscn to see it in action.

Clone this wiki locally