using Animancer; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Ether { public class StateMachine : Entity { [Label("实际移动速度")] public float DirectionSpeed = 0f; [Label("当前方向")] public Vector3 Direction = Vector3.down; private Dictionary allState = new Dictionary(); private StateBase defaultState; public StateBase DefaultState { get { if (defaultState == null) { allState.First(); defaultState.EnterState(); } return defaultState; } set { defaultState = value; } } private StateBase curState; public StateBase CurState { get { if (curState == null) { allState.First(); } return curState; } set { curState = value; } } private Animator Animator { get; set; } public AnimancerComponent Animancer { get; private set; } private void Awake() { Animator = GetComponent(); if (!Animator) { Animator = gameObject.AddComponent(); } Animancer = GetComponent(); if (!Animancer) { Animancer = gameObject.AddComponent(); Animancer.Animator = Animator; } } public void AddState() where T : StateBase, new() { Type stateType = typeof(T); AddState(stateType); } public void AddState(string stateType) { Type type = CommonTools.GetType(stateType); AddState(type); } public void AddState(Type stateType) { if (allState.ContainsKey(stateType)) { Debug.LogWarning($"该状态机({gameObject.name})已有该状态:{stateType}"); return; } StateBase state = (StateBase)PoolManager.Inst.Get(stateType); state.Init(this); allState.Add(stateType, state); } public void RemoveState() where T : StateBase, new() { Type stateType = typeof(T); RemoveState(stateType); } public void RemoveState(Type stateType) { if (!allState.ContainsKey(stateType)) { Debug.LogWarning($"该状态机({gameObject.name})没有该状态:{stateType}"); return; } allState[stateType].Dispose(); allState.Remove(stateType); } public bool SwitchState(bool resetState = false) where T : StateBase, new() { Type stateType = typeof(T); return SwitchState(stateType, resetState); } public bool SwitchState(Type stateType, bool resetState = false) { if (!allState.ContainsKey(stateType)) { Debug.LogError($"该状态机({gameObject.name})没有该状态:{stateType}"); return false; } if (CurState != null) { if (stateType == CurState.GetType() && !resetState) { return false; } if (!CurState.CheckStateIsCanSwitch()) { Debug.Log($"当前状态:{CurState}不能打断"); return false; } CurState.ExitState(); } var state = allState[stateType]; state.EnterState(); return true; } } }