I'm trying to implement a simple state machine based on a modified version of the state pattern using methods as states instead of classes, something like this:
private Action<Input> currentState;
private void NextState(Input i) {
currentState(i);
}
private void State1(Input i) {
if( i ... )
currentState = State1;
else
currentState = State2;
}
private void State2(Input i) {
if( i ... )
currentState = State1;
else
currentState = State2;
}
But it would be more elegant if I could do:
private void NextState(Input i) {
currentState = currentState(i);
}
private Func<xxx> State1() {
if( i ... )
return State1;
else
return State2;
}
But I don't know how to write this Func. Is there a way to do this?
If you want to use functions which return void, try using Action instead.
private Action State1() {
if( ... )
return State1Inner;
else
return State2Inner;
}
If you want to use a function which returns a function with it's own signature, you have to define a custom delegate type first. Here's a generic version:
public delegate State<T> State<T>(T input);
private State<int> State1(int input) {
if( ... )
return State1;
else
return State2;
}
This will help you avoid having inner state functions.
You might want to take a look at this article, which discusses the use of the yield statement for doing state machines. This is commonly done in, for example, in the Unity3d game engine. (another discussion here)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With