- Home /
reset bool on timer passed by ref
wanted to use a Coroutine to reset a bool value after a fixed time but it seams you cant pass in a ref to a IEnumerator
example
class foo
{
bool 1;
bool 2;
bool 3;
private bar()
{
// check something depending on check use bool 1 , 2 ,3 eg
1 = true;
StartCoroutine(Resetbool(1))
}
IEnumerator Resetbool(ref bool b)
{
yelid return new WaitForSeconds(5f)
b = false;
}
}
it doesn't have to be a coroutine im just trying to avoid haveing more then one method to reset each bool
$$anonymous$$aybe try a switch with an int:
IEnumerator Resetbool(int i) { yelid return new WaitForSeconds(5f) switch (i) { case (1): a = false;break; case (2): b = false;break; ... } }
}
you need to pass it as a ref as well don't you? - e.g. StartCoroutine(Resetbool(ref 1))
Answer by Bunny83 · Apr 04, 2018 at 01:17 AM
Coroutines can not have ref parameters as all parameters of a coroutine get converted to member variables of an implicit closure class. Ref or out parameters can not be "stored" in variables. Ref and out parameters are their own kind of "type". They are actually pointers to the memory location of the variable. Because of that ref and out parameters can not "leave" their scope. If it would be possible to store them in a member variable they could outlive the extent of the variable which is not possible / allowed in managed code as this would give you an invalid pointer.
The only way to accomplish what you want to do is using an actual closure around the variable you want to change. So you could change the signature of your method to take a delegate which you would execute when the timer has expired. You can use a lambda expression to create the closure. Something like this:
IEnumerator ExecuteIn5(System.Action aCallback)
{
yield return new WaitForSeconds(5f);
aCallback();
}
// [ ... ]
StartCoroutine(ExecuteIn5(()=>yourBool = false));
StartCoroutine(ExecuteIn5(()=>yourOtherBool = false));
Another similar but more restrictive way would be:
IEnumerator ResetBool(System.Action<bool> aCallback)
{
yield return new WaitForSeconds(5f);
aCallback(false);
}
// [ ... ]
StartCoroutine(ResetBool(a=>yourBool = a));
StartCoroutine(ResetBool(a=>yourOtherBool = a));
Finally your code in question is very confusing as it's not valid C# code. You can not have variable names which start with a number (or just consist of a number)