IndieGame/client/Assets/Ether/Scripts/Module/StateMachine/StateMachine.cs

153 lines
4.0 KiB
C#
Raw Normal View History

2024-10-11 10:12:15 +08:00

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<Type, StateBase> allState = new Dictionary<Type, StateBase>();
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<Animator>();
if (!Animator)
{
Animator = gameObject.AddComponent<Animator>();
}
Animancer = GetComponent<AnimancerComponent>();
if (!Animancer)
{
Animancer = gameObject.AddComponent<AnimancerComponent>();
Animancer.Animator = Animator;
}
}
public void AddState<T>() 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<T>() 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<T>(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;
}
}
}