- Home /
How do I play a sound when Health (or other variable) reaches a set number
Following on from an earlier question http://answers.unity3d.com/questions/8861/, my health decreases incrementally. As it does this the GUI health bar changes every time a multiple of 10 is reached (40, 30, 20...). I'd also like a sound to play each time it hits these markers. I tried to write a similar script as the one I have used to control the GUI, but it doesn't seem to work. Can you please tell me why? Thankyou!
var deathsound = AudioClip;
function update () {
if (HEALTH == 40) { audio.PlayOneShot(deathsound);
}
else if (HEALTH == 30) { audio.PlayOneShot(deathsound); } }
(Obviously I'd do this for each multiple of 10)
Could I also use this method to trigger an animation?
Answer by duck · Apr 27, 2010 at 03:43 PM
In your previous answer you have a function which is responsible for decreasing the health:
function subtract()
{
HEALTH -=1;
print ("health is now " + HEALTH);
}
This is where you should put your check (rather than in Update). In addition, if you want to perform the same action every time your health is a multiple of 10, there's a neat way of checking for this - it's called the modulus operator.
So you'd end up with something like this:
function subtract()
{
HEALTH -=1;
print ("health is now " + HEALTH);
if (HEALTH % 10 == 0) {
audio.PlayOneShot(deathsound);
}
}
wouldn't the audio file keep playing everytime the health variable ended in a "0"?
Your answer
Follow this Question
Related Questions
GUI Text Variable Counter In C# 1 Answer
Footsteps sound on collision problem, please help!!! 0 Answers
Multiple Audio Sources On One Object 0 Answers