Calling an if statement once even when it is calling every frame?

I got an if statement in the Update function which is based on another variable until it go over its limit. Example:

if(currentStamina < 50)

Now I want it to play an audio file for once, but because the currentStamina is changed every frame until it reached above the 50, it is calling the statement every frame.
Is there a way I can play the audio without having it interrupted and play it for once?

3 Answers

3

bool audioShouldPlay = true;

if((currentStamina < 50) && (audioShouldPlay)){
    //play audio
    audioShouldPlay = false;
}else if(currentStamina >= 50 && !audioShouldPlay){
    audioShouldPlay = true;
}

Put this in the update function, I think it’s the most logical way to handle this problem.
(It will only play the audio file when the health goes under 50, not when it already is under 50.)

If I understand your question and you want the sound to play while currentStamina < 50, but not restarting the sound ever frame? You can start it only if it isn’t already playing…

var audio : AudioSource;

function Update () {

   if(currentStamina < 50)
   {
      if(!audio.isPlaying)
      {
         audio.Play();
      }

   }
}

If you only want to play it once, you can use a boolean and only play the sound if the boolean hasn’t been set.

You could use a coroutine and wait - e.g.:

function Start()
{
    while(currentStamina < 50)
    {
       yield null;
    }
    //Play the audio
    

}

Or you could try this: function Start() { while(true) { while(currentStamina > 50) { yield null; } //Play sound when goes below 50 while(currentStamina <= 50) { yield null; } } } This will play the sound every time the stamina goes below 50, but only once each time