- Home /
play sound when kill enemy
hi Im building a 2d shooter and want to add a sound to a script that kills enemies but cant get it working.
This is the script
var hitPoints = 10;
function can_die (damage) { hitPoints -= damage; if( hitPoints < 1 ) { Destroy(gameObject, 0.0); } }
Ive tried adding
audio.PlayOneShot(Sound);
with an audio source but cant egt it working.
Any Ideas?
Thanks
Answer by crazyKnight · Oct 21, 2011 at 11:53 AM
the moment you destroy the object the script attached to it also get destroyed so no script no sound played
give a yield before destroying the object
function DestroyAfterYield(time : float)
{
audio.PlayOneShot(Sound);
yield WaitForSeconds(time);
Destroy(gameObject);
}
Thanks How would I incorporate this into my script with the hitpoints or does the DestroyAfterYield function just replace the can_die function?
Cheers
You could make that work even better, by doing this-
function DestroyAfterSound()
{
audio.PlayOneShot(Sound);
yield WaitForSeconds(Sound.length);
Destroy(gameObject);
}
Thanks a lot just having a little trouble (As javascript novice) working out how to put my original script var hitPoints = 10; function can_die (damage) { hitPoints -= damage; if( hitPoints < 1 ) { Destroy(gameObject, 0.0); } } together with your DestroyAfterSound script? Cheers
It's really simple! You just replace the line
Destroy(gameObject, 0.0);
with the line
DestroyAfterSound();
(or if you're doing the not automagic one, DestroyAfterYield(5))
Your answer
Follow this Question
Related Questions
Sound in unity3d 2 Answers
Why do sounds cancel out other sounds? 2 Answers
Sounds when mouse is over 1 Answer
How to test if a charactor is walking on terrain (to make a walking noise) 1 Answer
Audio Repeating. 1 Answer