- Home /
Strange sound error: sometimes rapid fires sound without stopping
Hello, I am adding a basic sound function to my players script. its pretty easy, if he gets hit, he takes damage, and when his damage is lowered every 5% or so, he makes a noise. It all works fine, but sometimes if he for instance takes damage and walks away from what hurt him (such as a fire), his "hurt sound" will keep rapid firing until I make him take damage again. Would anyone know what is causing this bug? his health will stop declining when he leave the fire, but the noise keeps playing. its really weird. Ive tried Audio.Stop but it just prevents the noise from playing. I tried doing a yield waitforseconds before audio.stop, but it gives me an error. Would anyone know what may cause this?
Thank you.
Here is the script that says to play the audio sound when he his hurt.
var HurtSound : AudioClip;
var CurrentHP : float = 100.0;
private var MaximumHP : int = 100.0;
function Update ()
{
// plays when player takes damage
if (CurrentHP % 5 == 1)
{
audio.PlayOneShot(HurtSound);
}
Answer by xandermacleod · Dec 15, 2013 at 02:11 PM
yes. it is because it is being called from your Update function.
even though you play the audio using audio.PlayOneShot, you are doing this every single frame when the if statement on line 10 returns true.
You might want to consider creating a bool flag
i.e. have a bool called something like HurtNoiseCanBePlayed. Make it true initially. Then check if its true before playing your audio (and if it is, then set it to false). Finally return it to being true at a convenient time that suits (such as in an else statement, when your if statement on line 10 returns false)
hello, sorry for the late reply. I added a new bool and created an if statement like this: function Update () { if (CurrentHP % 5 == 1 && HurtSoundCanPlay == false) {
audio.PlayOneShot(HurtSound);
HurtSoundCanPlay = true;
}
else
if (CurrentHP % 5 == 2 && HurtSoundCanPlay == true)
{
HurtSoundCanPlay = false;
}
It works just fine now. thank you for you help!
Your answer
![](https://koobas.hobune.stream/wayback/20220613124213im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Music stops other sounds from being played? 0 Answers
Screetching Sound While Walking? Why? 0 Answers
Unity White Screen Problem 2 Answers