using System; using System.Collections.Generic; using Sirenix.OdinInspector; namespace Ether { public abstract class StateMachine : Entity { private StateBase currentState; [ShowInInspector] [LabelText("状态列表")] public List allStates = new List(); private DictionaryEx allStatesDic = new DictionaryEx(); private void Awake() { foreach (var state in allStates) { state.StateMachine = this; allStatesDic.TryAdd(state.GetType().Name, state); } } public void ChangeState() where T : StateBase { ChangeState(typeof(T).Name); } public void ChangeState(string stateName) { if (allStatesDic.TryGetValue(stateName, out var state) && state != currentState) { currentState?.Exit(); currentState = state; currentState.Enter(); } } private void Update() { currentState?.Execute(); } } }