Avoiding Iterator never returns warnings

In this lecture we set up a coroutine for constant firing while the spacebar is depressed.

I use Rider or VS with Resharper as my IDEs, and I’m seeing Iterator never returns warnings by this approach.

private IEnumerator FireContinuously()
    {
        while (true)
        {
            var instance = Instantiate(projectilePrefab, transform.position, Quaternion
            .identity);
            Destroy(instance, projectileLifetime);

            var rb = instance.GetComponent<Rigidbody2D>();
            if (rb is not null)
            {
                rb.velocity = transform.up * projectileSpeed;
            }
            
            if (firingRate <= float.Epsilon)
            {
                firingRate = 1;
            }
            yield return new WaitForSeconds(1 / firingRate);
        }
    }

I can go round this by changing the while(true) to use our public bool that tells us if we should be firing or not, so the while becomes while(isFiring) instead.

That clears the warning, and seems to work in game. Question is, is that an OK practice, or am I likely to see any issues (performance or otherwise) with retesting isFiring at this point?

Thanks in advance!

Hi,

If the firingRate value does not change, it would be better to cache the WaitForSeconds object, for example, outside the while loop but within the FireContinuously method.

Apart from this little detail, I do not see why you should not use your solution. :slight_smile:

Did this help?


See also:

1 Like

This sent me scurrying off to test it, then to go read up on why I’d want to do that. Reduction in Garbage Collection came up, and that sent me reading even more :slight_smile:

Great answer, thanks for the feedback!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms