HI all, I’m creating a combat system right now, and for some reason, the simplest attack Coroutine I’ve built isn’t working as expected on my enemy object:
The Coroutine is called every update (which, now that I think about it, is probably the source to this issue), and is supposed to set a boolean so that it won’t execute a piece of code more than once per attack cooldown.
This is the code:
private IEnumerator AttackPattern()
{
if (!attacking)
{
GetComponent<EnemyFighterWrapper>().Attack(Direction.Left); //calls an attack animation etc
attacking = true;
}
yield return new WaitForSeconds(attackCooldown);
attacking = false;
}
What actually happens is weird: The first time the Coroutine gets called (proximity), the enemy plays it’s animation once, the attacking bool gets set to true, and after the attackCooldown ends, attacking gets set to true and the attacking animation starts once again. However, instead of it working the same as it did the first time, the attacking bool never gets set to true and the animation simply plays on loop.
I have a feeling this might be because the WaitForSeconds(attackCooldown) gets stacked because the coroutine get called every update? If that’s the case, how do I differentiate the timer from the coroutine, by using a different coroutine?
Anyway, I’m pretty stumped. Any help would be appreciated !
I don’t like coroutines for this sort of thing, as the edge case of what to do when something has to interrupt the coroutine is hard to reason about. Instead, I prefer cooldown timers:
Cooldown timers, gun bullet intervals, shot spacing, rate of fire:
Well looks like you’ve solved it.
It’s still frustrating to me, since I really feel like I’m never getting the concept of coroutines down… I always end up going around them.
Coroutines are super-easy and they are super useful. But they are not for everything. A ton of beginner tutorials reach for coroutines and overlook far simpler and more robust engineering solutions such as a simple timer or slowly-adjusted quantity.