SanAndreasUnity/Assets/Scripts/Utilities/StateMachine.cs

62 lines
1.5 KiB
C#
Raw Normal View History

2020-05-31 17:07:22 +00:00
using UnityEngine;
namespace SanAndreasUnity.Utilities
{
public class StateMachine {
IState m_currentState;
public IState CurrentState { get { return m_currentState; } }
bool m_isSwitchingState = false;
public float TimeWhenSwitchedState { get; private set; }
public long FrameWhenSwitchedState { get; private set; }
2021-09-19 22:44:31 +00:00
public void SwitchStateWithParameter(IState newState, object parameterForEnteringState) {
2020-05-31 17:07:22 +00:00
if(m_isSwitchingState)
throw new System.Exception("Already switching state");
if (newState == m_currentState)
return;
m_isSwitchingState = true;
IState oldState = m_currentState;
m_currentState = newState;
if (oldState != null)
{
// need to catch exception here, because otherwise it would freeze the state machine - it would
// no longer be possible to switch states, because 'm_isSwitchingState' is true
F.RunExceptionSafe(() =>
{
oldState.LastTimeWhenDeactivated = Time.time;
oldState.OnBecameInactive();
});
}
2020-05-31 17:07:22 +00:00
m_isSwitchingState = false;
this.TimeWhenSwitchedState = Time.time;
this.FrameWhenSwitchedState = Time.frameCount;
2021-09-19 22:44:31 +00:00
if (m_currentState != null)
{
m_currentState.ParameterForEnteringState = parameterForEnteringState;
m_currentState.LastTimeWhenActivated = Time.time;
2020-05-31 17:07:22 +00:00
m_currentState.OnBecameActive();
2021-09-19 22:44:31 +00:00
}
}
2020-05-31 17:07:22 +00:00
2021-09-19 22:44:31 +00:00
public void SwitchState(IState newState)
{
this.SwitchStateWithParameter(newState, null);
2020-05-31 17:07:22 +00:00
}
}
}