using System; using System.Collections.Generic; using UnityEngine; namespace Stary.Evo.FiniteStateMachine { public class FSMManager { public GameObject FSMMangerObject; private Dictionary controllers = new Dictionary(); private Dictionary states = new Dictionary(); private int nextControllerId = 0; private int nextStateId = 0; /// /// 创建FSMController /// /// 返回创建的FSMController的识别Int值 public int CreateFSMController() { if (FSMMangerObject == null) { Debug.LogError("FSM状态机还未初始化!!!"); return -1; } else { int id = nextControllerId++; GameObject newController = new GameObject("FSMController" + id); newController.transform.SetParent(FSMMangerObject.transform); var controller = newController.AddComponent(); controllers[id] = controller; return id; } } /// /// 销毁指定FSMController /// /// public void DestroyFSMController(int controllerId) { if (controllers.TryGetValue(controllerId, out var controller)) { GameObject.Destroy(controller.gameObject); controllers.Remove(controllerId); } else { Debug.LogError("该Id的FSMController不存在或已被销毁!!!"); } } /// /// 退出指定Controller中的所有状态 /// /// public void ExitAllStateInController(int controllerId) { if (controllers.TryGetValue(controllerId, out var controller)) { controller.ExitAll(); } else { Debug.LogError("该Id的FSMController不存在或已被销毁!!!"); } } /// /// 创建状态 /// /// 状态挂载的ControllerId /// 状态行为数据 /// public int CreateState(int controllerId, StateDateAction stateDateAction) { if (controllers.TryGetValue(controllerId, out var controller)) { // 创建state并将其添加到指定controller生命周期中 SingleState state = new SingleState(); state.stateDate = stateDateAction; controller.AddState(state); int id = nextStateId++; states[id] = state; return id; } else { Debug.LogError("该Id的FSMController不存在或已被销毁,状态初始化失败!!!"); return -1; } } /// /// 进入指定状态 /// /// public void EnterState(int stateId) { if (states.TryGetValue(stateId, out var state)) { state.Machine.Enter(state.GetType()); } else { Debug.LogError("该Id的状态不存在!!!"); } } /// /// 离开指定状态 /// /// public void ExitState(int stateId) { if (states.TryGetValue(stateId, out var state)) { state.Machine.Exit(state.GetType()); } else { Debug.LogError("该Id的状态不存在!!!"); } } /// /// 销毁指定状态 /// /// public void DestroyState(int stateId) { if (states.TryGetValue(stateId, out var state)) { states.Remove(stateId); } } // 将状态添加到FSMController public void AddStateToController(int controllerId, int stateId) { if (controllers.TryGetValue(controllerId, out var controller) && states.TryGetValue(stateId, out var state)) { controller.AddState(state); } } } }