Coroutine yields to a cooldown only once, what am I missing?

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:

GunHeat (gunheat) spawning shooting 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.

Coroutines in a nutshell:

https://discussions.unity.com/t/825667/6

https://discussions.unity.com/t/749264/9

This is a Good Thing™. When something is not the right tool, it’s GOOD not to use it.

1 Like

Niiiicccee at least some resources! anyway, thanks man…

Came to update you that the simple timer thing straight up worked and took like 3 seconds to hook up, and Then I noticed two things:

  1. what you wrote about not using the wrong tool, thanks for that, this is actually brilliant advice.
  2. noticed you were the one answering on all of the forums which is quite funny

Thanks man. On behalf of the next people to ask you about cooldown timers lol

1 Like