- Home /
Sound effect when health=0?
I am making a 2D game. When the player's health drops to 0 (when the player dies), I want a sound effect to play. How can I do it? Any kind of help would be appreciated. Thanks :)
Answer by Thomas-Hawk · Dec 20, 2016 at 07:11 PM
Attach an Audio Source component, and basically, in psuedocode:
AudioSource youraudiosource;
void Update () {
if (healthscript.currentHealth <= 0)
youraudiosource.Play();
}
I did that, but I can't attach the sound in the inspector. When I try this method, the sound plays regardless, even though I put it in
if(currentHealth <= 0) {
}
I fixed a few things. Now it plays it when the character dies, but it also plays it at the beginning.
Answer by teopotter88 · Dec 20, 2016 at 07:26 PM
Okay I fixed it. I used GetComponent to access the audio source, and then I used .play in the if statemnt and .Stop in void Start. Thanks for your help :)
I would recommend a prefab and instantiating it, as then you can play multiple sounds at once. you can Destroy the prefab after about 10 seconds, or a little more than however many seconds the sound will play. GameObject.FindObjectOfType<PlaySound> ().Play (click, vol)
EDIT: Unity Answers is messing up all my code... http://pastebin.com/53aVEZZ8
Your sound was probably playing at the start because the checkbox for 'Play on Awake' was ticked, by default it is always ticked so you need to uncheck it if you don't want it to play at the start.
Your answer
Follow this Question
Related Questions
SIMPLE player HP 1 Answer
Player Will not take any damage! 1 Answer
How to make player death sound effect / hitsound play once when function is called? 1 Answer
How can I lose health when my enemy collides with the player? 1 Answer
How to add Player health and ability to take damage from a cube? 2 Answers