52 lines
1.3 KiB
C#
52 lines
1.3 KiB
C#
using System;
|
|
using System.Collections;
|
|
|
|
namespace AibisDream.Framework
|
|
{
|
|
public class StateMachine<T> where T : Enum
|
|
{
|
|
public T CurState => _curState.GetState;
|
|
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();
|
|
}
|
|
|
|
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();
|
|
|
|
public IEnumerator Exit()
|
|
{
|
|
yield break;
|
|
}
|
|
}
|
|
} |