using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class FSMController : MonoBehaviour { private Dictionary states = new Dictionary(); public void AddState(SingleState state) { var type = state.GetType(); if (!states.ContainsKey(type)) { // 添加时初始化 state.Machine = this; state.OnInit(); states.Add(type, state); } else { Debug.LogError("该FSMController中已经添加过该状态!!!"); } } /* //public bool IsRunning() where T : SingleState => IsRunning(typeof(T)); //public void Enter() where T : SingleState => Enter(typeof(T)); //public void Exit() where T : SingleState => Exit(typeof(T)); //public void ForceEnter() where T : SingleState => ForceEnter(typeof(T));*/ public bool IsRunning(Type type) { if (states.ContainsKey(type)) { if (states[type].IsRunning) return true; } else { Debug.LogError("状态已不存在!!!"); } return false; } public void Enter(Type type) { if (states.ContainsKey(type)) { if (IsRunning(type)) { Debug.LogError("该状态正在进行,无法再次进入!!!"); return; } ForceEnter(type); } else { Debug.LogError("状态已不存在!!!"); } } public void ForceEnter(Type type) { if (states.ContainsKey(type)) { SingleState state = states[type]; state.OnEnter(); state.IsRunning = true; } else { Debug.LogError("状态已不存在!!!"); } } public void Exit(Type type) { if (states.TryGetValue(type, out SingleState state)) { if (!IsRunning(type)) return; state.IsRunning = false; state.OnExit(); } else { Debug.LogError("状态已不存在!!!"); } } public void ExitAll() { foreach (var state in states) { if (state.Value.IsRunning) Exit(state.Key); } } private void Update() { foreach (var state in states) { if (state.Value.IsRunning) state.Value.Update(); } } private void FixedUpdate() { foreach (var state in states) { if (state.Value.IsRunning) state.Value.FixedUpdate(); } } private void OnDestroy() { ExitAll(); // 遍历字典中的每个状态 foreach (var key in states.Keys.ToList()) { states[key].OnDestory(); // 将每个值设置为 null,释放引用 states[key] = null; } // 清空字典 states.Clear(); } }