78 lines
2.0 KiB
C#
78 lines
2.0 KiB
C#
using System.Collections.Generic;
|
||
|
||
//============================================================
|
||
//支持中文,文件使用UTF-8编码
|
||
//@author JiphuTzu
|
||
//@create 20220910
|
||
//@company Umawerse
|
||
//
|
||
//@description:
|
||
//============================================================
|
||
namespace Umawerse.FiniteStateMachines
|
||
{
|
||
public class FiniteStateMachine
|
||
{
|
||
private Dictionary<StateName, FiniteState> _states;
|
||
|
||
private FiniteState _current;
|
||
|
||
private StateName _currentName;
|
||
|
||
//private Dictionary<>
|
||
public FiniteStateMachine()
|
||
{
|
||
_states = new Dictionary<StateName, FiniteState>();
|
||
}
|
||
|
||
public void AddState(FiniteState state)
|
||
{
|
||
_states.Add(state.name, state);
|
||
}
|
||
|
||
public void SetState(StateName name, bool force = false)
|
||
{
|
||
if (force)
|
||
{
|
||
_currentName = StateName.none;
|
||
Update();
|
||
}
|
||
_currentName = name;
|
||
}
|
||
|
||
public T GetState<T>(StateName name) where T : FiniteState
|
||
{
|
||
if (_states.TryGetValue(name, out var state))
|
||
{
|
||
return state as T;
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
public StateName Update()
|
||
{
|
||
if (_current == null)
|
||
{
|
||
_states.TryGetValue(_currentName, out _current);
|
||
if (_current != null) _current.Enter();
|
||
else _currentName = StateName.none;
|
||
}
|
||
else if (_current != null)
|
||
{
|
||
if (_current.name == _currentName)
|
||
{
|
||
_currentName = _current.Update();
|
||
}
|
||
else
|
||
{
|
||
_current.Exit();
|
||
_states.TryGetValue(_currentName, out _current);
|
||
if (_current != null) _current.Enter();
|
||
else _currentName = StateName.none;
|
||
}
|
||
}
|
||
|
||
return _currentName;
|
||
}
|
||
}
|
||
} |