- Home /
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?
Answer by Unitraxx · Mar 20, 2013 at 09:56 PM
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.)
Answer by whebert · Mar 20, 2013 at 08:57 PM
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.
Answer by whydoidoit · Mar 20, 2013 at 08:47 PM
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(currentSta$$anonymous$$a > 50)
{
yield null;
}
//Play sound when goes below 50
while(currentSta$$anonymous$$a <= 50)
{
yield null;
}
}
}
This will play the sound every time the sta$$anonymous$$a goes below 50, but only once each time
Your answer
Follow this Question
Related Questions
Check renderer.enabled statement from another object 3 Answers
How do you say in between for an if statement? 2 Answers
empty component var 1 Answer
Can I call sounds from other script? 1 Answer
Audio issue - Trying Waitforseconds 0 Answers