# Create a stack driven coroutine based state machine for Unity

I am working on a game where I am using a coroutine based state machine which is mostly a multi class implementation of this link. I am using it because it allows me to create multi frame sequences.

I wanted to know how would I go about making a stack based machine, so that I can overlay game states such as when I want to pause the game to show a menu i can run a pause menu state pausing the running game state, while still allowing the state objects to be rendered in the background

Here is the code I am using for a state:

public abstract class State {

[Inject]
MonoBehaviour gameObject;

[Inject]
public EventSystem eventSystem;

StateMachine parent;

public State(StateMachine p)
{
parent = p;
}

public abstract IEnumerator Enter();

public abstract IEnumerator Exit();

public abstract IEnumerator Update();

public IEnumerator Run()
{
yield return gameObject.StartCoroutine(Enter());
while(parent.CurrentState.GetType() == GetType())
{
yield return gameObject.StartCoroutine (Update ());
}
yield return gameObject.StartCoroutine (Exit());
}
}


State machine run function

 State Current //The current state , the one at the top of the stack
while(Current!=null)
{
yield return Component.StartCoroutine(Current.run());
}


The problem with this approach is as soon as the state machine's current state changes (That is when i push it down the stack adding a new state on top) , the while loop in the Base state class's run method will end and will call the exit coroutine causing the state to end which is undesirable as according to the stack pattern the state should be paused

Moreover as coroutines work in unity, the yield return statement(in the state-machine) wont return until the previous started coroutine exits , which is currently as of now responsible for starting the states .

My question is how do i alter this code so as to pause the previous state (that will be pushed into the stack) instead of exiting it and starting anew state

this implementation works fine if there is to be only a single state in the memory

• Your question is interesting, but I had to reread it 5 times to understand it. Can you please try to make it more understandable? – Maxim Kamalov Sep 6 '16 at 1:19
• @MaximKamalov what according to you should i change to make it more understandable ? – B0rn2C0de Sep 6 '16 at 13:16
• Add more context to the second code; elaborate the last paragraph. – Maxim Kamalov Sep 6 '16 at 15:14
• @MaximKamalov edited – B0rn2C0de Sep 6 '16 at 19:24