Search code examples
c#yield-return

How do I wait until a bool is true in unity?


I am trying to make it so that when a button is pressed, the text would update.

My code:

public Text TextField;

public bool narrationGoing = true;

public void SetText(string text)
{
    TextField.text = text;
}

public void ResumeNarration()
{
    narrationGoing=true;
}

IEnumerator WaitNarration()
{
    narrationGoing = false;
    Debug.Log(narrationGoing);
    yield return new WaitWhile(() => narrationGoing == false);
}

void Start()
{
    Narration();
}

void Narration()
{
    SetText("HeLlO wOrLd");
    StartCoroutine(WaitNarration());
    SetText("The button worked!");
}

However, when I launch the game it triggers the "WaitNarration()" coroutine, because it does write "false", but then it skips over the yield completely. I've tried to find a solution but sadly nothing worked, does anyone have an answer for how I can fix this? Thank you in advance! Also, ResumeNarration() is a function for the button, that's why it's not triggered in the code.


Solution

  • You can yield inside of a while loop until the condition is met.

    IEnumerator WaitNarration()
    {
        Debug.Log("WaitNarration started");
        
        while (!narrationGoing)
        {
            yield return null;
        }
    
        Debug.Log("WaitNarration complete");
    }