IEnumerator for fire trap

I’m trying to use an IEnumerator to trigger a fire trap:

private IEnumerator TrapTriggerTime()
    {
        activeTime = Random.Range(2, 6);
        _active = true;
        fireTrap.SetBool("activated", true);
        yield return new WaitForSeconds(activeTime);

        activeWait = Random.Range(5, 11);
        yield return new WaitForSeconds(activeWait);
        fireTrap.SetBool("activated", false);
        _active = false;
    }

So when it is active the animation for fire should play for between 2 and 5 seconds. After this _active should be set false so the fire trap cannot damage the player, it should then be inactive for 5 to 10 seconds. In the scene the animation is rapidly flickering between on and off.

Does yield return new WaitForSeconds stay on that line of code or does it execute the next line immediately? If it does execute immediately, is this why the off and on animation are trying to play at the same time? Lastly am I close with what I want it to do?

waitforseconds is self-explanatory, waits for given seconds then moves into the next line.

are you calling TrapTriggerTime coroutine multiple times? like on trigger events or in update loop?

In update all I have is this:

private void Update()
    {
        StartCoroutine(TrapTriggerTime());
    }

In OnTriggerEnter2D, I’m checking if the collider has collided with the player tag. If that is true, another if statement checks if _active is true, which is set in TrapTriggerTime coroutine, then damage is dealt to the player health script.

do you know that Update runs on every frame?

so in every frame, you are starting TrapTriggerTime coroutine, before the one ends, the other one begins.

that’s why its flickering.

Make a conditional start, and make sure it fires the coroutine just once.