Home > database >  How can I make a foreach loop pause until my Coroutine is finished?
How can I make a foreach loop pause until my Coroutine is finished?

Time:07-06

Hey there I have a foreach loop that loops through strings in a list in unity. I want to make it so it will yield or pause until a certain amount of seconds have passed. The script is really long so I will just include the necessary parts.

    foreach (string s in ScriptLines)
    {                
            if (s.Contains("Wait"))
            {
                Run = false;
                Index1 = s.IndexOf(":");
                WaitTime = int.Parse(s.Substring(Index1   1));
                if (ShowDebugStatus == true)
                {
                    Debug.Log("Attempting to wait "   WaitTime   " seconds.");
                }
                StartCoroutine(Wait());
            }
     }

And the wait() is above the loop and has this code:

    IEnumerator Wait()
    {
        yield return new WaitForSeconds(WaitTime);
        Run = true;
        if (ShowDebugStatus == true)
        {
            Debug.Log("Wait finished.");
        }
    }

Any help is appreciated.

CodePudding user response:

You can place the entire foreach loop in a coroutine and remove the Wait coroutine.

private IEnumerator ProcessScriptLines(IEnumerable<string> scriptLines)
{
    foreach (var line in scriptLines)
    {
        if (line.Contains("Wait"))
        {
            // get waitTime and such..
            
            yield return new WaitForSeconds(waitTime);
        }
    }
}

and start the coroutine where you were iterating before.

StartCoroutine(ProcessScriptLines(ScriptLines));
  • Related