- Home /
How to pass Predicate to a Coroutine?
I'm trying to send a bool function as a parameter in a coroutine and i learned that using predicate is the solution to send bools (i think?....) however I'm unable to get it working because I'm not understanding what the "object" parameter is. It isn't the class?
IEnumerator Pause( Predicate<WhatsThisParameter?> condition )
{
while (!condition)
{
yield return null;
}
}
As in the function would be evaluated multiple times in the coroutine?
correct, so i could send different bool functions to the condition parameter and evaluate them multiple times during the while statement.
is that function dynamically created on the fly, or is it a member function for some class?
If it's part of a component script, you could just pass that component's instance. I'm having trouble imagining a situation where the best-practice solution for this situation requires a reference to the function itself.
Answer by Bunny83 · Nov 01, 2016 at 11:30 PM
The generic Predicate type is a special delegate type that always returns a boolean and takes a single generic parameter. If you just want a delegate that takes no parameter at all you should simply use System.Func<bool>
instead.
Also a delegate is a "method pointer" so you have to actually execute it to get the return value
IEnumerator PauseWhile( System.Func<bool> condition )
{
if (condition == null)
yield break;
while (!condition())
yield return null;
}
This can be used like this:
yield return StartCoroutine(PauseWhile(()=>YourConditionHere));
A Predicate always takes a parameter. For example:
Predicate<int> condition = (p) => p > 10
if(condition(5)) // returns "false"
if(condition(11)) // returns "true"
The type Predicate<int>
would be equivalent to the type Func<int, bool>
. So it's a delegate to a method that takes an int parameter and returns a bool.
Keep in mind that you can assign any kind of method that matches the delegate signature, not only anonymous methods / lambda expressions:
private bool Test(int aParam)
{
return aParam == 3;
}
Predicate<int> condition = Test;
condition(3) // --> returns "true"
Perfect! Thank you very much, I actually tried func<> and now realize it wasn't working initially because i didn't add the parenthesis to execute the function. Thank you for explaining predicates too. Awesome answer! $$anonymous$$uch appreciated!
Your answer
![](https://koobas.hobune.stream/wayback/20220612095837im_/https://answers.unity.com/themes/thub/images/avi.jpg)