NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Framework/Pattern/StatePattern.cs

54 lines
1.4 KiB
C#
Raw Normal View History

2024-02-21 19:34:58 +08:00
using Cysharp.Threading.Tasks;
2023-08-22 19:08:45 +08:00
namespace Framework
{
// implement a finite state machine class
2023-10-19 15:00:19 +08:00
2023-08-22 19:08:45 +08:00
public interface IState
{
2024-02-21 19:34:58 +08:00
bool exitFinished { get; }
2023-08-22 19:08:45 +08:00
void OnEnter();
void OnUpdate(float deltaTime);
void OnExit();
}
public class StateMachine
{
private IState _currentState;
private IState _previousState;
2024-02-21 19:34:58 +08:00
public async UniTask ChangeState(IState newState)
2023-08-22 19:08:45 +08:00
{
if (_currentState != null)
{
_currentState.OnExit();
2024-02-21 19:34:58 +08:00
while (!_currentState.exitFinished)
{
UniTask.NextFrame();
}
2023-08-22 19:08:45 +08:00
}
_previousState = _currentState;
_currentState = newState;
_currentState?.OnEnter();
}
public void Update(float deltaTime)
{
if (_currentState != null)
{
_currentState.OnUpdate(deltaTime);
}
}
public void RevertToPreviousState()
{
ChangeState(_previousState);
}
public IState GetCurrentState()
{
return _currentState;
}
}
2023-10-19 15:00:19 +08:00
}