StartCoroutine: waiting for one sequence to be over

Hello,

I have set up my game such that all GUI animations are done using StartCoroutine method. Occasionally, GUI components sort of gets “stuck” together, completely freezing the game.

Now, when I have a line such as the following:

		if(_raycastHit.transform.tag.CompareTo("QuitButton") == 0){
			StartCoroutine(GAME_done ("MENU"));
			StartCoroutine(PAUSEMENU_done ());
			StartCoroutine (MAINMENU_start ());
		}

How should I alter the code such that StartCoroutine (MAINMENU_start ()); will be called after StartCoroutine (PAUSEMENU_done ()); is finished? Or is this not something that I can do?

Thanks!

Use yield with the coroutines, as described in the docs.

     yield return new StartCoroutine(GAME_done ("MENU"));
     yield return new StartCoroutine(PAUSEMENU_done ());
     yield return new StartCoroutine (MAINMENU_start ());

You could put your Animations inside another Coroutine and use yield to not start them unless the previous one has completed. Something like this should work:

	bool gameDone;       // set each of these to true
	bool pauseDone;      // when completing the
	bool mainMenuDone;   // relevant coroutine

	void YourQuitFunction ()
	{	
		StartCoroutine("DonePauseMainSequence");
	}

	IEnumerator DonePauseMainSequence()
	{
		StartCoroutine(GAME_done ("MENU"));
		while(!gameDone)
			yield return null;
		
		StartCoroutine(PAUSEMENU_done ());
		while(!pauseDone)
			yield return null;
		
		StartCoroutine (MAINMENU_start ());
		while(!mainMenuDone)
			yield return null;
	}

Though I would be tempted to only have a single coroutine and do something like:

	public Animation gameDone;
	public Animation pause;
	public Animation mainMenu;

	void Start ()
	{	
		StartCoroutine("DonePauseMainSequence");
	}

	IEnumerator DonePauseMainSequence()
	{
		gameDone.Play(); // StartCoroutine("gameDone"); would also be a choice (but doesn't seem needed?
		while(gameDone.isPlaying)
			yield return null;
		
		pause.Play();
		while(pause.isPlaying)
			yield return null;
		
		mainMenu.Play();
		while(mainMenu.isPlaying)
			yield return null;
	}

Answer inspired from learnings of Richard Fine on AltDevBlog