NewN_UAVPlane/Assets/Zion/Scripts/Adam/FiniteStateMachines/FiniteStateMachine.cs

78 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}
}