Easily extendable pure C# State Machine implementation for Unity.
- Install the Git Dependency Resolver.
- Import it in Unity with the Unity Package Manager using this URL:
https://github.com/DatLycan/Unity-StateMachine.git
public struct FirstState : IState {
public void OnEnter() => Debug.Log("Entered First State");
public void FixedUpdate() { }
public void Update() => Debug.Log("Update First State");
public void LateUpdate() { }
public void OnExit() => Debug.Log("Exited First State");
}
public struct SecondState : IState {
public void OnEnter() => Debug.Log("Entered Second State");
public void FixedUpdate() { }
public void Update() => Debug.Log("Update Second State");
public void LateUpdate() { }
public void OnExit() => Debug.Log("Exited Second State");
}
public class MyClass : MonoBehaviour {
private StateMachine stateMachine;
private bool toggleState;
private void Start() {
IState firstState = new FirstState();
IState secondState = new SecondState();
stateMachine = new StateMachine(entryState:firstState);
stateMachine.AddTransition(from:firstState, to:secondState, new Condition(() => toggleState));
stateMachine.AddTransition(from:secondState, to:firstState, new Condition(() => toggleState));
}
private void Update() => toggleState = Input.GetKeyDown(KeyCode.Space);
}
public class MyClass : MonoBehaviour {
private StateMachine stateMachine;
private bool toggleState;
private void Start() {
IState firstState = new StateBuilder()
.WithEnter(() => Debug.Log("Entered First State"))
.WithExit(() => Debug.Log("Exited First State"))
.WithUpdate(() => Debug.Log("Update First State"))
.Build();
IState secondState = new StateBuilder()
.WithEnter(() => Debug.Log("Entered Second State"))
.WithExit(() => Debug.Log("Exited Second State"))
.WithUpdate(() => Debug.Log("Update Second State"))
.Build();
stateMachine = new StateMachine(entryState:firstState);
stateMachine.AddTransition(from:firstState, to:secondState, new Condition(() => toggleState));
stateMachine.AddTransition(from:secondState, to:firstState, new Condition(() => toggleState));
}
private void Update() => toggleState = Input.GetKeyDown(KeyCode.Space);
}
The FixedUpdate(), Update() and LateUpdate() methods are getting called by the according subsystem in the standard Unity PlayerLoop, e.g. every frame.
- Inspired by adammyhre.
- Using mob-sekai's Git Dependency Resolver For Unity