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.
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?