Skip to content

Instantly share code, notes, and snippets.

@tedigc
Created December 17, 2021 23:13
Show Gist options
  • Save tedigc/a314fb724727c36d84e8bce50223b29e to your computer and use it in GitHub Desktop.
Save tedigc/a314fb724727c36d84e8bce50223b29e to your computer and use it in GitHub Desktop.
namespace rpg {
public class StateMachine<T> {
private T entity;
private State<T> currentState;
private State<T> previousState;
private State<T> globalState;
public StateMachine(T entity, State<T> initialState, State<T> globalState = null) {
this.entity = entity;
this.currentState = initialState;
this.globalState = globalState;
initialState?.Enter(entity);
globalState?.Enter(entity);
}
public void Update(float dt) {
if(globalState != null) globalState.Update(entity, dt);
if(currentState != null) currentState.Update(entity, dt);
}
public void Draw() {
if(globalState != null) globalState.Draw(entity);
if(currentState != null) currentState.Draw(entity);
}
public void ChangeState(State<T> newState) {
previousState = currentState;
previousState.Exit(entity);
currentState = newState;
currentState.Enter(entity);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment