- Home /
Sound not working with onTriggerEnter
I'm trying to have an audio file play when it's destroyed but its not working.
Here is my code.
I have the audioclip set up here.
public AudioClip deathSound;
And here is the code that has the audio file in.
switch(other.tag)
{
case "EnemyProjectile":
audio.PlayOneShot(deathSound);
Instantiate(Explosion, transform.position, Quaternion.identity);
Destroy(other.gameObject);
GameManager.PlayerDies();
Destroy(gameObject);
break;
Is the audio source a component to one of the objects that you are destroying? If it is, that's why it won't play... a destroyed object no longer exist so it can not play sounds either. You'll need a separate object to play the sound, one that is not being destroyed.
Would it be better to have a separate gameobject that handles all the sounds then?
you could try and destroy when on the completion of the sound playing. you should be able to tell when the clip is playing. once it completes then destroy your objects. then you don't need to have a separate object for sound.
Answer by fafase · Nov 12, 2013 at 08:38 PM
@tkbn is leading you to the right path.
You can fix this simply changing which object will play:
AudioSource.PlayClipAtPoint(deathSound, transform.position);
The good point of that method, it is static, so it does not depend on an object. What it does is create a new object that plays the sound and dies when the sound is over.
I wasn't familiar with @fafase 's alternative, but it definitely seems to be the best match for your scenario.
Thanks for all the replies and help. I'll be trying this out when I get a chance. I didn't know about that one, thanks a lot.
Your answer
![](https://koobas.hobune.stream/wayback/20220613121643im_/https://answers.unity.com/themes/thub/images/avi.jpg)