Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using UniRx;
- namespace AnimalSimulator.Infrastructure
- {
- public class StateMachine
- {
- public readonly Subject<IExitableState> OnStateChanged = new Subject<IExitableState>();
- private readonly Dictionary<Type, IExitableState> _states;
- private IExitableState _activeState;
- public StateMachine(IExitableState[] states) =>
- _states = states.ToDictionary(state => state.GetType());
- public void Enter<TState>() where TState : class, IState =>
- ChangeState<TState>().Enter();
- public void Enter<TState, TPayload>(TPayload payload) where TState : class, IPayloadedState<TPayload> =>
- ChangeState<TState>().Enter(payload);
- private TState ChangeState<TState>() where TState : class, IExitableState
- {
- _activeState?.Exit();
- var state = GetState<TState>();
- _activeState = state;
- OnStateChanged.OnNext(_activeState);
- return state;
- }
- private TState GetState<TState>() where TState : class, IExitableState =>
- _states[typeof(TState)] as TState;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment