Wait for a bool to be true

Hello.

i have a for loop that loop through an array to look if it’s ready by a bool function.

inside this bool function i need to wait untill another bool become tru to continue and return true…

i’m wondering…to how is the best way to do this.

Is all of that supposed to happen on the main thread? You could then take a look at coroutines and the variety of yield instructions. Generally, you can also implement the logic in Update, but I could imagine it’ll be more straight forward in a coroutine.

Can you not do something similar like that?

bool outputBoolB = false ;
if ( waitingForBoolA )
{
    outputBoolB = DoSomething () ;
}
public class MyClassA
{
    private MyClassB _myClassB = new MyClassB();
    private bool IsReadyToContinue()
    {

        // i need to wait "isReady" here
        // then return true


        return false;
    }

}

public class MyClassB
{
    public bool isReady;


    private void DoSomething()
    {
        // load resources and change the bool to true

        isReady = true;
    }
}

this is what i mean…

Unity - Scripting API: WaitUntil You could use WaitUntil. The other option would be just execute the code when you would normally set the bool to true instead.

//Useful when we want to hold a IEnumerator method which is using for/while loop until the passed "checkMethod" returns true
//It is needed coz in IEnumerator method we cant pass boolean variable by reference


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using kFramework;
public class CoroutineLoopTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(WrongWayToPauseLoop());
        StartCoroutine(CorrectWayToPauseLoop());
    }
    // Update is called once per frame
    IEnumerator WrongWayToPauseLoop()
    {
        print("Start");
        int index = 0;
        while (index <= 20)
        {
            //This will not stop while loop or for loop
            yield return null;
            print("WrongWay Index= " + index);
            index++;
        }
        print("End");
    }
    IEnumerator CorrectWayToPauseLoop()
    {
        print("Start");
        int index = 0;
        while (index <= 20)
        {
            //Hold the coroutine loop until space button is clicked
            yield return WaitUntilTrue(IsSpaceKeyPressed);
            print("CorrectWay Index= " + index);
            index++;
        }
        print("End");
    }
    bool IsSpaceKeyPressed()
    {
        return Input.GetKeyDown(KeyCode.Space);
    }

       public IEnumerator WaitUntilTrue(Func<bool> checkMethod)
        {
            while (checkMethod() == false)
            {
                yield return null;
            }
        }


}
1 Like