Play sound each x seconds on condition

Hi,

I have a variable integer called “fear”. This is set to 0 but when playing the game it can go up until 98.

I want to play an audio clip each 5 seconds once fear is above or equal to 30 but under or equal to 60. How do I do this? I either end up playing it once or it keeps repeating every frame because it’s in the update function. I can’t figure out how to fix this.

Script:

function Update() {
   playBreathing();
}

function playBreathing() {
    if(fear >= 30 && fear <= 60) {
        AudioSource.PlayClipAtPoint(breathing1, transform.position);
        yield WaitForSeconds(5);
    }
}

One method would be to set up a boolean that stores if the current AudioClip is still playing or not.

private var isPlaying : boolean = false;

function Update() {
     playBreathing();
}

function playBreathing() {
     if(!isPlaying && fear >= 30 && fear <= 60) {
         isPlaying = true;
         AudioSource.PlayClipAtPoint(breathing1, transform.position);
         yield WaitForSeconds(audio.clip.length);
         isPlaying = false;
     }
}

There are several ways you could do this. One way would be to spawn playBreathing as a coroutine (basically a thread). Make sure to only spawn it once.