Pro_Unit

StateMachine

Jul 22nd, 2021
822
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. using UniRx;
  6.  
  7. namespace AnimalSimulator.Infrastructure
  8. {
  9.     public class StateMachine
  10.     {
  11.         public readonly Subject<IExitableState> OnStateChanged = new Subject<IExitableState>();
  12.         private readonly Dictionary<Type, IExitableState> _states;
  13.         private IExitableState _activeState;
  14.  
  15.         public StateMachine(IExitableState[] states) =>
  16.             _states = states.ToDictionary(state => state.GetType());
  17.  
  18.         public void Enter<TState>() where TState : class, IState =>
  19.             ChangeState<TState>().Enter();
  20.  
  21.         public void Enter<TState, TPayload>(TPayload payload) where TState : class, IPayloadedState<TPayload> =>
  22.             ChangeState<TState>().Enter(payload);
  23.  
  24.         private TState ChangeState<TState>() where TState : class, IExitableState
  25.         {
  26.             _activeState?.Exit();
  27.  
  28.             var state = GetState<TState>();
  29.             _activeState = state;
  30.            
  31.             OnStateChanged.OnNext(_activeState);
  32.  
  33.             return state;
  34.         }
  35.  
  36.         private TState GetState<TState>() where TState : class, IExitableState =>
  37.             _states[typeof(TState)] as TState;
  38.     }
  39. }
RAW Paste Data