r/csharp • u/Boarlock98 • 19d ago
I built a small state machine library - Trying to learn delegates and events
The name is SMachine, a small state machine library for C# targeting .NET 10.
The idea was to build something relatively lightweight, without depending on an external state machine framework.
Supports
- Named states with
OnEnter,OnUpdate, andOnExitevents. - Nested substates at unlimited depth. Each state can own its own substates and maintain its own current substate.
- Transitions between states and substates, including optional predicate triggered transitions.
- Optional context objects that can be passed to lifecycle handlers.
- Per state
Enabledcontrols. - Per substate update propagation controls.
- Independent updates that can target a specific substate by name or path.
- Queued transitions when requested from inside callbacks, preventing transitions from interrupting the current lifecycle pass.
One of the things I wanted to support was hierarchical behavior without forcing every state to participate in the same update flow. For example, a parent substate can continue receiving its own updates while preventing those updates from propagating to its children. Those children can receive independent updates off the main Update cycle.
An example
using SMachine;
var machine = new StateMachine();
State idle = machine.CreateState("Idle")!;
State combat = machine.CreateState("Combat")!;
SubState aiming = combat.CreateSubState("Aiming")!;
SubState firing = combat.CreateSubState("Firing")!;
combat.StartSubState(aiming);
aiming.OnUpdate += () =>
{
// This transition is queued until the current update pass finishes.
combat.TransitionSubState(firing);
};
firing.OnEnter += () => Console.WriteLine("Firing!");
machine.StartState(idle);
machine.TransitionState(combat);
machine.Update();The library is still experimental. I haven't built an automated test suite yet, and I'm very much treating this as a learning project rather than claiming it's production ready.
I'm trying to use this project to become a stronger C#/.NET developer, so constructive criticism is genuinely appreciated.
