Using local variables inside functions/coroutines as much as possible good practice?

Here are the global variables inside that are used.

private Gun _activeGun
private float _shotDuration;
private LayerMask _castMask;
    private IEnumerator HandleActionState(Gun gun, GunAction gunAction, LayerMask mask)
    {
        yield return gun.HandleAction(gunAction, mask);
        EndCurrentAction();
    }
   private IEnumerator HandleShoot(float duration, LayerMask shotMask)
    {
        Shoot(shotMask);
        float timeElapsed = 0;
        while (timeElapsed < duration)
        {
            timeElapsed += Time.deltaTime;
            yield return null;
        }
    }

I want to know if defining as many local variables inside a function is preferred because of readability and flexibility even if it’s extra checks. In this case it’s nice to have since fire rate can be flexible as well as the gun. Instead of active gun I could have an int that represents what the player has equipped in holster or even call it from another class.

My question is at what point does it become too excessive?
The only reason outside of having to type less code is if there is some kind of external change needed inside a coroutine that the variable needs.

I.e. a coroutine that automatically shoots every 2 seconds of the active gun in the players hands.

I’m not sure why you would use a coroutine for this in the first place. It really ought to be something just handled on a per-frame basis in Update.

In any case a variable should just be in the appropriate scope. Is it only used in a method? Scope it to the method. Is it used across a class? Scope it to the class. Don’t overthink these things.

1 Like

Spiney already said it, so I won’t repeat it. Though I’d like to add the coroutines technically are not methods or functions. They are statemachine objects. Local variables as well as arguments to a coroutine will end up as fields of a compiler generated class. Those fields are of course scoped to that class since they are only used inside that class by the statemachine which resembles your original “method”.

If you want to understand how coroutines work, I wrote this coroutine crash course some time ago. Though this is kinda irrelevant for the question of scope. As it was arleady mentioned, scope your variables as small as possible and as wide as absolutely necessary.

Also, having coroutines messing with instance members of the host class can cause a lot confusion, especially when there are multiple coroutines running at the same time. It’s not really a race condition but it creates situations which are hard or even impossible to reason about when you can not easily determine in which order things are happening.

3 Likes