r/codereview • u/Boarlock98 • 22d ago
Made a small easy to use State Machine.
Wanted a state machine tool for myself in various projects but also for other developers, been having fun with it and learning more C# concepts.
Features
- Enum-keyed states, using a non boxing key internally, the underlying value and the enum's type are packed into a struct, so no enum ever gets boxed
- Nested substates, each with it's own events and it's own current substate
- Predicate transitions that are safe to poll every frame (optional)
- Optional context objects passed to handlers on enter, update and exit; sealed record types with value equality and built in deconstruction, up to 10 values
- Per state
Enabledflag and per substate update propagation IndependentUpdateto tick a specific substate by a path of enum keys, mixing enum types freely across levels- Transitions requested from inside callbacks are queued and run after the current pass, so handlers can request transitions without breaking the machine
TryCreateState,TryGetStateandStartStatereturnfalseinstead of throwing for common mistakes
Here's a quick use guide I made to demonstrate usage:
using SMachine;
public enum States { Idle, Combat }
public enum CombatSubs { Melee }
private string Name;
private int HeroAttack;
public void Initialize()
{
var machine = new StateMachine();
// States belong to the machine
State idle = machine.CreateState(States.Idle);
State combat = machine.CreateState(States.Combat);
// Substates belong to a state
SubState melee = combat.CreateState(CombatSubs.Melee);
// Create a context object to pass to your handlers (optional)
var ctx = new Context<string, int>("Hero", 10);
// Subscribe to the events
combat.OnEnter += () => Console.WriteLine("Combat has begun!");
melee.OnEnterContext += (ctx) => {
// I recommend using pattern matching for ease of use and safety
if (ctx is Context<string, int>(string name, int attack))
{
Name = name;
HeroAttack = attack;
}
};
// Start your states
machine.StartState(States.Combat); // This fires OnEnter
combat.StartState(CombatSubs.Melee, ctx); // This fires OnEnterContext
// Subscribe to the OnUpdateContext event
melee.OnUpdateContext += HeroAttack;
// Call Update on our machine for Combat state to update, then Melee
machine.Update(ctx);
}
public void HeroAttack(BaseContext ctx)
{
// We can also access context directly after casting
var typed = (Context<string, int>)ctx;
Console.WriteLine($"{typed.Data1} hits Goblin for {typed.Data2} damage!");
}
There are other features like Update Propagation, Independent Updates, and the Context type itself. I explain it all in detail over on my GitHub.
Let me know what you guys think, have any suggestions or just want to tell me I suck at programming (please don't be mean).
3
Upvotes
2
u/Exotic-Ninja5489 19d ago
making `StartState` return false instead of throwing for common mistakes might bite you in production tbh. silent failures in state machines are usually a nightmare to debug when a transition just quietly doesnt happen.
1
u/LaurenceDarabica 20d ago
What's wrong with Stateless ?
1
u/Angelvin_Pinheiro 19d ago
Wait, in your example `combat.CreateState(CombatSubs.Melee)` returns a `SubState`, can a `SubState` also have its own substates or is the hierarchy strictly two levels deep?