49 lines
1.2 KiB
C#
49 lines
1.2 KiB
C#
|
|
namespace Framework
|
||
|
|
{
|
||
|
|
// implement a finite state machine class
|
||
|
|
public class StatePattern
|
||
|
|
{
|
||
|
|
public interface IState
|
||
|
|
{
|
||
|
|
void OnEnter();
|
||
|
|
void OnUpdate(float deltaTime);
|
||
|
|
void OnExit();
|
||
|
|
}
|
||
|
|
|
||
|
|
public class StateMachine
|
||
|
|
{
|
||
|
|
private IState _currentState;
|
||
|
|
private IState _previousState;
|
||
|
|
|
||
|
|
public void ChangeState(IState newState)
|
||
|
|
{
|
||
|
|
if (_currentState != null)
|
||
|
|
{
|
||
|
|
_currentState.OnExit();
|
||
|
|
}
|
||
|
|
|
||
|
|
_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;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|