using System; using System.Collections.Generic; using System.Text; namespace PlayerSampleMission1CSharp { public abstract class FSMState { protected object owner = null; public FSMState(object owner) { this.owner = owner; } public object Owner { get { return owner; } set { owner = value; } } public abstract void Enter(); public abstract void Exit(); public abstract void Update(); public abstract Type getNextTransition(); } public class FSMMachine { // Déclaration of the variables protected List states = new List(5); // List of all the states protected FSMState currentState = null; // Current state protected FSMState defaultState = null; // state by default public void AddState(FSMState state) { states.Add(state); } public void SetDefaultState(FSMState state) { this.defaultState = state; } public FSMState getCurrentState() { return this.currentState; } private FSMState existsState(Type type) { foreach (FSMState state in states) { if (state.GetType() == type) return state; } return defaultState; } public void Update() { // If there is at least one state if (states.Count != 0) { // If it is the first iteration if (currentState == null) { // current state = default state currentState = defaultState; // even default state was not define if (currentState == null) // we stop return; } Type oldStateType = currentState.GetType(); Type newStateType = currentState.getNextTransition(); // If the state has changed if (oldStateType != newStateType) { currentState.Exit(); // exit the current state currentState = existsState(newStateType); // go to the next state currentState.Enter(); // enter the state } // update the state currentState.Update(); } } } }