How should I loop a coroutine like this?

Let’s say I have an shooting option in my game, and I’m using a coroutine and a boolean to handle with it. I can imagine two ways of doing this.

One is starting the coroutine in Awake (or Start, or OnEnable, its your choice here) and then loop inside the coroutine:

private void Awake()
{
    StartCoroutine(ShootCoroutine());
}

private IEnumerator ShootCoroutine()
{
    while (true)
    {
        if (shouldShoot)
        {
            // Code for instantiate the bullet here...
        }

        yield return new WaitForSeconds(delayToNextShoot);
    }
}

The other one is restarting the coroutine (you can make it using StopCoroutine too, but whatever for this question):

private void Update()
{
    if(canShoot && shouldShoot)
    {
        StartCoroutine(ShootCoroutine());
    }
}

private IEnumerator ShootCoroutine()
{
    // Code for instantiate the bullet here...

    canShoot = false; // Prevent the restart of the coroutine in the next frame

    yield return new WaitForSeconds(delayToNextShoot);

    canShoot = true;
}

Is there a “way to go” solution in this case? If yes, between those options, which one should I use?
Please share any other solution that you want to.

Thanks.

No need for coroutines for something as simple as a gun timer.

Cooldown timers, gun bullet intervals, shot spacing, rate of fire:

GunHeat (gunheat) spawning shooting rate of fire:

3 Likes

Thank you. I always used to use coroutines in everything that involves handling with time.

Now talking about performance, just for knowledge, if you have to use a coroutine like the ones of the question for some reason, would you set to start the coroutine only once, or would you keep restarting it?

Coroutines are just a tool.

You reach for a tool for a specific purpose.

Your question is like asking “If I’m using a screwdriver do I turn it to the right or to the left?”

It completely depends on what you’re doing.

You might even use a screwdriver to open a can of paint.

Sometimes you don’t even need a screwdriver: you can just turn the screw by hand.

Keep in mind that coroutines are NEVER needed. They just are useful in certain contexts.

Coroutines in a nutshell:

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

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

Splitting up larger tasks in coroutines:

https://discussions.unity.com/t/840656/2

Coroutines are NOT always an appropriate solution: know when to use them!

“Why not simply stop having so many coroutines ffs.” - orionsyndrome on Unity3D forums

https://discussions.unity.com/t/857304/4

https://discussions.unity.com/t/849607/7

Our very own Bunny83 has also provided a Coroutine Crash Course:

https://discussions.unity.com/t/coroutines-ienumerator-not-working-as-expected/237287/3

1 Like

Thanks for share that line of thinking and for all references!