How to simplify this

Hi,

I have a classic chat between characters :

blablablabla
while ((!Input.GetKeyDown(KeyCode.Return) && !Input.GetMouseButtonDown(0)))yield;
blablablabla
while ((!Input.GetKeyDown(KeyCode.Return) && !Input.GetMouseButtonDown(0)))yield;

etc.

I’m trying to stop repeat the “while” each time but I don’t know how I can do it because it has to be here and not in a function. (otherwise chat dont wait for enter to continue). Does anyone have a simple solution or maybe there is no solution ? thanks

A while loop makes sense when you’re repeating things, such as steps in a conversation. You also need to be able to allow multiple frames to pass while waiting for input. Here’s a way to simplify things a bit. It relies on the ability to yield until another coroutine completes… I’ve not compiled or tested this, but it gives you the basic idea.

void Start()
{
    StartCoroutine(PlayConversation());
}


IEnumerator WaitForKeypress()
{
    while (!Input.GetKeyDown(KeyCode.Return) && 
           !Input.GetMouseButtonDown(0)) yield return null;
}


IEnumerator PlayConversation()
{
    List<string> conversation = 
      new List<string> { "blablablalba", "bla bla bla", "bla, blabla, blablabla" };
    int index = 0;

    while (index < conversation.Count)
    {
      ... display item at index - e.g. Debug.Log(conversation[index]);

      // wait for keypress
      yield return StartCoroutine(WaitForKeypress());

      // point to the next item in the conversation
      index += 1;
    }
}