- Home /
How to play a sound once in Update?
I have a character that whenever its health is below 0.1, he dies and then a sound comes in. The problem is that the sound keeps playing every single frame instead of just once. This is the script.
public float health;
public AudioSource sound;
void Update()
{
if(health < 0.1f)
{
if(!sound.isPlaying)
{
sound.Play();
}
}
}
Thanks!
Answer by Rechronicle · Oct 21, 2021 at 04:36 PM
create a bool isSoundPlayed. Reset the bool if the health goes back up.
You might want to use the event to check if the player health goes to 0, instead of checking on it every frame.
Your answer
![](https://koobas.hobune.stream/wayback/20220613044445im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to check if a audio clip had ended via scripting? 2 Answers
enable components with same name via script... 3 Answers
How to correctly add audio to rolling ball 1 Answer
Is it possible to scroll in a InputField using a script? 0 Answers
Script and Start function of script are running, but Update function is not? 0 Answers