81 lines
2.4 KiB
C#
81 lines
2.4 KiB
C#
using System;
|
|
using System.Collections;
|
|
|
|
namespace AibisDream.Framework
|
|
{
|
|
public class StateMachine<T> where T : Enum
|
|
{
|
|
public T CurState => _curState.GetState;
|
|
public bool HasState => _curState != null;
|
|
public IState<T> CurrentStateObj => _curState;
|
|
public event Action<T> OnStateSwitch;
|
|
|
|
private IState<T> _curState;
|
|
private readonly Func<T, string, IState<T>> _createState;
|
|
|
|
public StateMachine(Func<T, string, IState<T>> createState)
|
|
{
|
|
_createState = createState;
|
|
}
|
|
|
|
public IEnumerator Init(T initState)
|
|
{
|
|
return SwitchState(initState);
|
|
}
|
|
|
|
public IEnumerator SwitchState(T nextState, string args = "")
|
|
{
|
|
if (_curState != null && CurState.Equals(nextState)) yield break;
|
|
|
|
yield return _curState?.Exit();
|
|
_curState = _createState.Invoke(nextState, args);
|
|
OnStateSwitch?.Invoke(nextState);
|
|
yield return _curState.Enter();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 强制设置内部状态对象,不触发 Exit / Enter / OnStateSwitch。
|
|
/// 用于读档等需要绕过正常状态过渡的场景。
|
|
/// </summary>
|
|
public void SetStateImmediate(T state, string args = "")
|
|
{
|
|
_curState = _createState.Invoke(state, args);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读档恢复:跳过前一状态的 Exit,直接进入目标状态的 EnterImmediate。
|
|
/// </summary>
|
|
public IEnumerator SwitchStateImmediate(T nextState, string args = "")
|
|
{
|
|
if (_curState != null && CurState.Equals(nextState)) yield break;
|
|
|
|
_curState = _createState.Invoke(nextState, args);
|
|
OnStateSwitch?.Invoke(nextState);
|
|
yield return _curState.EnterImmediate();
|
|
}
|
|
|
|
public IEnumerator QuitState()
|
|
{
|
|
yield return _curState?.Exit();
|
|
_curState = null;
|
|
}
|
|
}
|
|
|
|
public interface IState<out T> where T : Enum
|
|
{
|
|
public T GetState { get; }
|
|
public void SetArgs(string args) {}
|
|
public IEnumerator Enter();
|
|
|
|
/// <summary>读档恢复:跳过过渡动画,直接到达终态。</summary>
|
|
public IEnumerator EnterImmediate()
|
|
{
|
|
yield break;
|
|
}
|
|
|
|
public IEnumerator Exit()
|
|
{
|
|
yield break;
|
|
}
|
|
}
|
|
} |