Use of Coroutine or Loop for on/off timer?

I have a script for a laser beam that turns on and off after a certain amount of time as passed. Currently I am using two coroutines that call one another (code on bottom). Would it be better/more efficient to use a timer and loop instead? Why or why not?

Coroutine code:

IEnumerator activateBeam() //Sets the components of the laser beam to be active and begins a countdown to call disableBeam
    {
        Debug.Log("Enabled");
        visuals.SetActive(true);
        physics.SetActive(true);
        yield return new WaitForSeconds(activeDuration);
        StartCoroutine(disableBeam());
    }
    IEnumerator disableBeam() //Sets the components of the laser beam to be disabled and begins a countdown to call activateBeam
    {
        Debug.Log("Disabled");
        visuals.SetActive(false);
        physics.SetActive(false);
        yield return new WaitForSeconds(pauseDuration);
        StartCoroutine(activateBeam());
    }

That works but personally I would simplify it to one coroutine that contains this loop:

while(true)
{
  // do the enable code here
  yield return new WaitForSeconds(activeDuration);
  // do the disable code here
  yield return new WaitForSeconds(pauseDuration);
}

There is no way you could ever see even the tiniest performance difference between mine and yours, but the code becomes much cleaner: one function with one area of concern.

This way you can also save the Coroutine reference that StartCoroutine() returns to you and use that value to stop it in the future, if you want.

1 Like