Coroutine Issue

So I am working on designing boss levels for my game right now. The bosses have X amount of stages based on their health. When X amount of damage is done, Transition() is calledto transition to the next phase. While transitioning the sprite renderer fades out, then fades in with a new boss sprite. So this required me to use coroutines to handle the lerping. I haven’t worked alot with coroutines and they are looping for some reason. This is resulting in AlterState() being called numerous times by the coroutine, the end result of which is the boss goes from Stage 1 all the way to the last stage.

void Update () {
        // Check if boss is transitioning
        if (isTransitioning)
        {
            // Check if transitioning in or out
            if (transitioningOut)
                StartCoroutine(TransitionOut());
            else
                StartCoroutine(TransitionIn());
        }
}

private IEnumerator TransitionOut()
    {
        float alpha = GetComponent<SpriteRenderer>().material.color.a;
        for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / transitionDuration)
        {
            Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha, 0.1f, t));
            GetComponent<SpriteRenderer>().material.color = newColor;
            yield return null;
        }

        // Set transitioning out to false
        transitioningOut = false;
    }

    private IEnumerator TransitionIn()
    {
        // Alter the current stage
        AlterStage();

        float alpha = GetComponent<SpriteRenderer>().material.color.a;
        for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / transitionDuration)
        {
            Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha, 1f, t));
            GetComponent<SpriteRenderer>().material.color = newColor;
            yield return null;
        }

        // Set transitioning to false
        isTransitioning = false;
    }

private void Transition()
    {
        // Set the boss as transitioning
        isTransitioning = true;
        // Set boss as transitioning out
        transitioningOut = true;
    }

    private void AlterStage()
    {
        switch (currentStage)
        {
            case BossState.Stage1: // Stage 1
                currentStage = BossState.Stage2;
                break;
            case BossState.Stage2: // Stage 2
                currentStage = BossState.Stage3;
                break;
            case BossState.Stage3: // Stage 3
                break;
        }
    }

All help is appreciated, thanks in advance.

Set isTransitioning to false after you fall inside the first if statement

Ah yeah, that will do it. Wasn’t sure how they worked, I figured you had to continue calling it to make it go but I suspected it might be the cause of the issue. Changed it up and that worked well, thanks.