
If (Trigger = PressSwitch) goto on // Transitions go here: Yield return null // This means "Wait until a

protected override IEnumerable WalkStates()Ĭonsole.WriteLine("off.") // State entry actions
#Finite state automata unity how to
Just to clarify, I've added some comments to the first state to help you understand how to use this. This state machine is controlled simply by sending triggers to it: var sm = new Lamp() Protected override IEnumerable WalkStates() Triggers (or events, or actions, whatever) that our
#Finite state automata unity code
I've commented the code of the first state and its transitions below the next states follow the same pattern. A trigger becomes a property or field of type Action, decorated with an attribute called Trigger. In YieldMachine code, we write a single method for all state-related behavior, in which we commit the horrible atrocity of using goto for each state. Notice that this state machine has 2 triggers and 3 states. Some shameless self-promo here, but a while ago I created a library called YieldMachine which allows a limited-complexity state machine to be described in a very clean and simple way. Return other != null & this.CurrentState = other.CurrentState & this.Command = other.Command StateTransition other = obj as StateTransition Return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode() Public StateTransition(ProcessState currentState, Command command) For this simple state machine, I prefer a transition table, which is very easy to represent using a Dictionary: using System You can convert this to C# in a handful of ways, such as performing a switch statement on the current state and command, or looking up transitions in a transition table.

So it would be great if someone could provide a C# source code-example that realizes a simple state machine with perhaps 3,4 states, just to get the gist of it. I found this discussion about state machines & iterator blocks in c# and tools to create state machines and whatnot for C#, so I found a lot of abstract stuff but as a noob, all of this is a little confusing. Or do I have a misconception of state machines and their common use? In the sense that the examples do change state but that's only represented by changing the value of a variable (and allowing different value- changes in different states), while usually, a state machine should also change its behavior, and behavior not (only) in the sense of allowing different value changes for a variable depending on the state, but in the sense of allowing different methods to be executed for different states. Again thanks for the examples, they have been very helpful and with the following, I don't meanĪren't the currently given examples, as far as I understand them & state-machines, only half of what we usually understand by a state-machine?
