Destroy Game Object on Collision BUT Play Sound

Hi,

I’m only just starting working with audio with Unity and I’ve come across a bit of an issue, which I’m sure everyone gets to at some point.

I have a torpedo that hits an asteroid, the said asteroid is destroyed, but I want to play the sound of the explosion - but yeah, I know, the asteroid along with the Audio Source is destoyed too! Meaning no sound is played :frowning:

Most of the examples I saw online delays the destroying of the game object which then gives time for the explosion to play - but… I don’t like it. My explosion sound last just shy of 2 seconds and delaying the removal of the asteroid object is too obvious, obviously :wink:

I did find an alternate method, but I don’t get how to use it:
https://bladecast.pro/unity-tutorial/how-to-play-sound-collision-even-destroy

Surely there’s an easier method?

Can anyone help please?

Cheers, Jay.

I would make a little “destructo” audio controller that goes on a sub-GameObject within your asteroid.

When you destroy your asteroid, look for this destructo audio controller and say “PLAY!”

The PLAY! function would contain steps to:

  • start the audiosource
  • de-parent itself (call transform.SetParent(null);)
  • Destroy() itself with a few seconds delay

Just be sure to call that BEFORE you Destroy() the root asteroid, so that the audiosource is orphaned and can play.

What’s wrong with the link you found?
You can find audio managers on the asset store, but they all have various ways of handling the audio.

If you don’t mind the limitations of the free version, this might work for you. We’ve used the paid version for 2D games.

Thanks Kurt, it worked. I think it was similar to the link I provided.

The difficulty for me was to understand how to access a function from another script and call it. I’ve never done it before and there was a lot of confusing info online, but I found a great tutorial on it here:

Which for me at least, made more sense :slight_smile:

Phew!

It is always the same in Unity, reaching to any public methods in other script instances. ALWAYS the same:

Referencing variables, fields, methods (anything non-static) in other script instances:

https://discussions.unity.com/t/833085/2

https://discussions.unity.com/t/839310