All I can find online talking about await
in async
is teaching me how to "wait for a certain period of time", which is not what I want.
I want it to wait until a certain condition is met.
Just lile
yield return new WaitUntil(()=>conditionIsMet);
in Coroutine
.
I want to do something like
await Task.WaitUntil(()=>conditionIsMet);
Is such thing possible?
Could somebody please be so kind and help me out?
Thank you very much for your help.
Wouldn't this basically simply be something like
public static class TaskUtils
{
public static Task WaitUntil(Func<bool> predicate)
{
while (!predicate()) { }
}
}
though for the love of your CPU I would actually rather give your task certain sleep intervals like
public static class TaskUtils
{
public static async Task WaitUntil(Func<bool> predicate, int sleep = 50)
{
while (!predicate())
{
await Task.Delay(sleep);
}
}
}
and now you could e.g. use something like
public class Example : MonoBehaviour
{
public bool condition;
private void Start()
{
Task.Run(async ()=> await YourTask());
}
public async Task YourTask()
{
await TaskUtils.WaitUntil(IsConditionTrue);
// or as lambda
//await TaskUtils.WaitUntil(() => condition);
Debug.Log("Hello!");
}
private bool IsConditionTrue()
{
return condition;
}
}