I have a design pattern question. Im trying to implement a Finite State Machine.
Its working but i havent tried on on more advanced projects. My question is
At the moment this is the flow:
State Manager calls every fram Current State.UpdateState()
In this method the state can be changed wherever inside UpdateState.
When this happens following code executes
Exit CurrentState
Enter NewState
Set NewState to Current State
and then the UpdateState would finish executing (in what is now previous state).
This cant be right?
So i should do something like
State Manager Updates every fram
{
CurrentState.Update();
//After update check if change state
If(NewState != CurrentState)
{
CurrentState.Exit();
NewState.Enter();
CurrentState = NewState;
}
}
OR should i change the state before updating state?
The usual solution is to use a property or state change method to call your Enter and Exit methods whenever a state change should occur.
private State m_CurrentState;
public State CurrentState
{
get { return m_CurrentState; }
set
{
if (m_CurrentState == valse)
return;
if (m_CurrentState != null)
m_CurrentState.Exit();
m_CurrentState = value;
if (m_CurrentState != null)
m_CurrentState.Enter();
}
}
In case your Enter and Exit method should be informed about the previous / new state you might want to pass those to the Enter / Exit methods:
set
{
if (m_CurrentState == valse)
return;
if (m_CurrentState != null)
m_CurrentState.Exit( value );
var old = m_CurrentState;
m_CurrentState = value;
if (m_CurrentState != null)
m_CurrentState.Enter( old );
}
So in this case “Enter” gets a reference to the old state and “Exit” the reference to the new state.
To change the state you simply set “CurrentState” to a new state.