/* author: YKMoon * 状态机 * 初始化需要手动添加状态信息 AddState * Update里面来调用状态机运行StateMachineUpdate */ using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace YKMoon { public enum FSMUpdateMode { Normal, Unscaled, } public class UFSMState { public Action onUpdate; public Action onEnterState; public Action onExitState; public int stateID = -1; public UFSMState() { } public UFSMState(int stateID, Action onEnterState, Action onUpdate, Action onExitState) { this.stateID = stateID; this.onEnterState = onEnterState; this.onExitState = onExitState; this.onUpdate = onUpdate; } } public class UFSMCore { public UFSMState currentState = new UFSMState(); public int lastState; /// /// 进入当前状态的时间点Time.time /// protected float timeEnteredState = 0; private Dictionary stateDict = new Dictionary(); public int currentStateID { get { return currentState.stateID; } set { //UnityEngine.Debug.LogErrorFormat("当前状态 {0} 输入状态 {1} == {2}", currentState.stateID, value, currentState.stateID == value); if (currentState.stateID == value) return; if (!stateDict.ContainsKey(value)) { #if UNITY_EDITOR Debug.LogErrorFormat("StateMachine Does not contain ({0}) state!", value); #endif return; } lastState = currentState.stateID; timeEnteredState = Time.time; if (currentState.onExitState != null) { currentState.onExitState.Invoke(); } currentState = stateDict[value]; if (currentState.onEnterState != null) { currentState.onEnterState.Invoke(); } } } public UFSMCore() : this(null, null) { } public UFSMCore(System.Action EarlyGlobalUpdate, System.Action LateGlobalUpdate) { this.EarlyGlobalUpdate = EarlyGlobalUpdate; this.LateGlobalUpdate = LateGlobalUpdate; } /// /// 添加状态 /// /// true, 如果添加成功, false 添加失败. /// 状态ID. /// 进入状态时调用 /// 更新时调用 /// 出状态时调用. public bool AddState(int stateID, Action onEnterState, Action onUpdate, Action onExitState) { if (stateDict.ContainsKey(stateID)) return false; UFSMState newState = new UFSMState(stateID, onEnterState, onUpdate, onExitState); stateDict.Add(stateID, newState); return true; } public void Clear() { stateDict.Clear(); } /// /// 状态机更新,这个默认在Update里面,如果不想这样就覆盖Update /// public void StateMachineUpdate(float deltaTime) { EarlyGlobalUpdate?.Invoke(deltaTime); currentState.onUpdate?.Invoke(deltaTime); LateGlobalUpdate?.Invoke(deltaTime); } /// /// (float deltaTime) /// public System.Action EarlyGlobalUpdate; /// /// (float deltaTime) /// public System.Action LateGlobalUpdate; } }