I'm trying to play a sound when an enemy is destroyed. I created a child game object and put this in the OnEnterCollision2D function:

 private void OnCollisionEnter2D(Collision2D collision)
    effect = GetComponent<AudioSource>();
    effect.transform.parent = null;
    Destroy(effect.gameObject, 1);

However, it doesn't seem to fire this event when the bullet enters the enemy character.


1 Answer 1


It looks like this code expects the audio source to be in two different places:

  1. GetComponent<AudioSource> says the audio source is on "this" object, the one that just collided with something.

  2. effect.transform.parent = null and Destroy(gameObject) seem to assume the audio source is on a child game object, which can "eject" to safety before the parent object is destroyed.

These two assumptions aren't compatible. Either the source is actually on a child object and the first line returns null, or the source is on "this" game object and it goes down with the ship, getting destroyed this frame. Both possibilities lead to no sound being played.

To know how to fix it, we'll need to see a bit more about how your scene is set up.

You can also consider using the static method AudioSource.PlayClipAtPoint() to fire a "posthumous" sound without manually managing another game object.

  • \$\begingroup\$ AudioSource.PlayClipAtPoint() worked for me. Thanks. \$\endgroup\$
    – John Meyer
    Commented Oct 29, 2017 at 0:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .