Skip to content

[FR] Improve custom state documentation / functionality #65

Description

@Nitero

I want to use a state machine for my game states. This means that the states should execute some logic, so I looked into custom state classes. Unfortunately I had some trouble setting them up because there was no complete example of how to use custom states in a state machine.

This is what I initially tried. It did not throw any errors, but the OnLogic method on the selection state was never called:

internal class GameStateController : IStartable, ITickable
{
    private readonly StateMachine<GameState> _stateMachine = new();

    public void Start()
    {
        SelectionState selectionState = new SelectionState();
        PlacementState placementState = new PlacementState();

        _stateMachine.AddState(selectionState);
        _stateMachine.AddState(placementState);

        _stateMachine.SetStartState(selectionState);
        _stateMachine.Init();
    }

    public void Tick()
    {
        _stateMachine.OnLogic();
    }
}

So I realized it was probably using the instances as a keys but not hooking them up at all. Using the state names as keys seemed to fix the issue:

internal class GameStateController : IStartable, ITickable
{
    private readonly StateMachine _stateMachine = new();

    public void Start()
    {
        _stateMachine.AddState(nameof(SelectionState), new SelectionState());
        _stateMachine.AddState(nameof(PlacementState), new PlacementState());

        _stateMachine.SetStartState(nameof(SelectionState));
        _stateMachine.Init();
    }

    public void Tick()
    {
        _stateMachine.OnLogic();
    }
}

This is a bit awkward though. My assumption was that if I just use custom states I wouldn't need an additional enum or string and could just use the state classes directly. Could you maybe flesh out the documentation on this part, or even add some kind of helper that let's us use states directly without having to specify keys?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions