-
Notifications
You must be signed in to change notification settings - Fork 0
Home
birdimus edited this page Aug 10, 2016
·
7 revisions
Welcome to the unity-application-state-machine wiki!
I'm thinking something like this
public class ApplicationStateMachine{
public enum TransitionResponse{Failure, Success}
int currentStateId = 0;
ApplicationState[] states;
void UpdateFSM(){
ApplicationState currentState = states[currentStateId];
currentState.UpdateState();
for(int i=0; i<states.Length; i++){
if(i != currentStateId){
states[i].BackgroundUpdate(currentState);
}
}
}
TransitionResponse TransitionToState(int targetStateId){
///make sure we are pointing to a valid state
if(targetStateId <0 || targetStateId >= states.Length){
return TransitionResponse.Failure;
}
ApplicationState targetState = states[targetStateId];
ApplicationState currentState = states[currentStateId];
/// we should not permit re-entry on application states, since they are globally scoped
/// we could specifically permit this is the specif state allows it as a 'reset'
if(targetState == currentState){
return TransitionResponse.Failure;
}
currentState.Exit();
targetState.Enter();
currentStateId = targetStateId;
return TransitionResponse.Success;
}
}
public abstract class ApplicationState{
protected enum TransitionStatus{Idle, Enter, Active, Exit}
protected TransitionStatus status;
public virtual void Exit(){
status = TransitionStatus.Exit;
}
public virtual void Enter(){
status = TransitionStatus.Enter;
}
public virtual void UpdateState(){
}
public virtual void BackgroundUpdate(ApplicationState currentState){
}
}