Multiple coroutine issues

I’m trying to create a Zoom feature in my game where if you right click, it will “zoom” in and if you let go it with zoom out.

Here is the Zoom code:

public IEnumerator Zoom(float targetFOV) {
        for(int i = 0; i < targetFOV; i++) {
            Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, targetFOV, i / targetFOV);
            yield return new WaitForEndOfFrame();
        }
    }

It works fine if you click in and out slowly, but when you try to do this quick, the transition becomes choppy. I understand that it’s because the for loops are overlapping each other, but I’m not sure the best way to fix the issue.

My only idea is to use some bool checks, but if you release the button and the bool doesn’t allow you to execute the zoom out code, it will just remain zoomed in.

In this particular case, I’d recommend not using a coroutine at all. At any given moment there is a target FOV, and you’re just toggling between them.

bool zoomToggle = false;
void Update() {
if (Input.GetKeyDown("z")) zoomToggle = !zoomToggle; // or whaetver your toggling trigger is
float targetFOV = 15f;
if (zoomToggle) targetFOV = 45f;

            Camera.main.fieldOfView = Mathf.MoveTowards(Camera.main.fieldOfView, targetFOV, zoomingSpeed * time.deltaTime);
}

This method will work no matter when you switch the bool; it’ll always move towards whatever the current target zoom level is.