Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class StateMachine<S, T> : MonoBehaviour
- {
- protected State<S, T> _currentState;
- protected List<IStateMachineSubscriber> _stateMachineSubscribers = new List<IStateMachineSubscriber>();
- protected Queue<T> _commands = new Queue<T>();
- private T _activeCommand;
- //TODO: probably make 'em protected
- public State<S, T> _initState;
- public AbstractStateFactory<S, T> _stateFactory;
- public State<S,T> CurrentState { get { return _currentState; } }
- public delegate void StateEnterEventHandler(S state);
- public delegate void StateExitEventHandler(S state);
- public delegate void StateChangeEventHandler(S prevState, S newState);
- public event StateEnterEventHandler OnStateEnter;
- public event StateExitEventHandler OnStateExit;
- public event StateChangeEventHandler OnStateChange;
- public virtual void Start()
- {
- Debug.Log("State Machine created!");
- }
- public virtual void HandleCommand(T command)
- {
- if (command.Equals(_activeCommand))
- {
- Debug.LogWarning($"Received command {command.ToString()}, but the same command is already ACTIVE");
- return;
- }
- if (_commands.Contains(command))
- {
- Debug.LogWarning($"Received command {command.ToString()}, but the same command is already IN QUEUE");
- return;
- }
- _commands.Enqueue(command);
- Debug.Log($"Enqueued command: {command.ToString()}");
- }
- public virtual void Update()
- {
- if (_commands.Count > 0)
- {
- var commandCandidate = _commands.Peek();
- if (ProcessCommand(commandCandidate))
- {
- _commands.Dequeue();
- Debug.Log($"Dequeued command {commandCandidate.ToString()}");
- }
- }
- else
- {
- _activeCommand = default(T);
- }
- }
- public virtual void SubscribeToStateMachine(IStateMachineSubscriber subscriber)
- {
- if (!_stateMachineSubscribers.Contains(subscriber))
- {
- _stateMachineSubscribers.Add(subscriber);
- }
- }
- public virtual void UnsubscribeToStateMachine(IStateMachineSubscriber subscriber)
- {
- if (_stateMachineSubscribers.Contains(subscriber))
- {
- _stateMachineSubscribers.Remove(subscriber);
- }
- }
- #region Protected methods
- protected bool ProcessCommand(T command)
- {
- foreach (var subscriber in _stateMachineSubscribers)
- {
- while (!subscriber.IsReady)
- {
- return false;
- }
- }
- var newState = _currentState.CheckTransCondition(command);
- if (!_currentState.StateName.Equals(newState))
- {
- _activeCommand = command;
- OnStateExit?.Invoke(_currentState.StateName);
- var prevState = _currentState;
- _currentState = _stateFactory.CreateState(newState);
- OnStateEnter?.Invoke(_currentState.StateName);
- OnStateChange?.Invoke(prevState.StateName, _currentState.StateName);
- Debug.Log("Switched to " + newState.ToString());
- }
- return true;
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement