- Home /
Generic Cooldown IEnumerator?
So I'm trying to make a generic function for all my cooldowns.
I basically have:
public bool check;
public float coolDown = 0.5f;
void start()
{
check = false;
}
void update()
{
if (!check)
{
check = true;
StartCouroutine(CoolDown(check, coolDown));
}
}
IEnumerator CoolDown(bool action, float coolDown)
{
yield return new WaitForSeconds(coolDown);
action = false;
}
But the action = false does not work. If I used check = false during the CoolDown it will work. Is there a way for it to change the value of check without calling check directly?
I've heard people were having problems if the coroutine method that takes parameters
CoolDown(bool action, float coolDown)
is not public. Can you try to make it public and try again ?
Answer by whydoidoit · Feb 21, 2014 at 08:44 AM
So unfortunately what you want to do is pass a reference to the CoolDown function, rather than the bool directly - however this is not supported with these "special" classes in .NET.
You have a couple of choices:
Pass a class containing the bool and check that:
public class CoolDownGuard { public bool action; } IEnumerator CoolDown(CoolDownGuard guard, float coolDown) { yield return new WaitForSeconds(coolDown); guard.action = false; }
2) Use a generic "run after a period of time" function:
public IEnumerator DoAfter(float delay, System.Action operation) {
yield return new WaitForSeconds(delay);
operation();
}
StartCoroutine(DoAfter(coolDown, ()=>check = false));
The second one worked like a charm, thanks! I'm also wondering if using coroutines for these kinds of operations is best practice.
Before using coroutines I implemented cooldowns by using:
public float timeStamp = 0.0f;
public float coolDown = 3.0f;
...
if(Input.Get$$anonymous$$eyDown("w"))
{
if (Time.time > timeStamp)
{
timeStamp = Time.time + coolDown;
//do stuff
}
}
Is there a difference with going with the coroutine method or this time stamp method?
I use the Coroutine method all the time - it's much much cleaner to read and no big overhead.
Your answer
Follow this Question
Related Questions
Toggling bools automatically using coroutines 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
make events occur only at specific times 1 Answer
C# - Coroutines for Abilities 1 Answer