Waiting for Input via Coroutine

Hello All,

So I’ve been working on a rudimentary dialogue system. Basically it works by displaying text sequentially, and to do this I am using a coroutine.

using UnityEngine;
using System.Collections;

public class TalkTrigger : MonoBehaviour {

	bool currentlyTalking = false;
	public string[] dialogue;
	// Use this for initialization
	void Start () {

	void OnTriggerEnter2D() {


		GUIManager.PushTextBox(GUIInterface.instance.genericTextBox, GUIInterface.instance.genericText, "press SPACE to talk to me");
		currentlyTalking = true;


	void OnTriggerStay2D(){
		if(Input.GetKeyUp(KeyCode.Space) && currentlyTalking == true)
			Debug.Log("Should be talking now...");

	//this is where sequential dialogue goes

	IEnumerator DialogueStart(){

		foreach(string text in dialogue)

			yield return StartCoroutine(Dialogue(text);

		currentlyTalking = false;


	IEnumerator Dialogue(string text){
		GUIManager.PushTextBox(GUIInterface.instance.genericTextBox, GUIInterface.instance.genericText, text);
		yield return new WaitForSeconds(5);

		GUIManager.PopTextBox(GUIInterface.instance.genericTextBox, GUIInterface.instance.genericText);



now this script works as expected, but, when i try to change:

yield return new WaitForSeconds(5);


yield return Input.GetKeyDown(KeyCode.Space);

All of the text flies by, and doesn’t actually wait for the user’s next press.

Is there something about the default input methods that allow this to happen? Is there a way to control the floodgate so that the coroutine pauses at each point I need user input?

Thanks in advance

If you check the scripting reference you’ll see that Input.GetKeyDown returns a bool, not an IEnumerator. Since this is the case, you want to use a while loop and yield while that condition is false. Ex:

IEnumerator WaitForKeyDown(KeyCode keyCode)
    while (!Input.GetKeyDown(keyCode))
        yield return null;

Now you can wait for whatever kind of input you want by calling this:

yield return StartCoroutine(WaitForKeyDown(KeyCode.Space));

Inside your coroutine you could do this:
yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.A));