In this article I will show how I setup the sound effects in my 2D Space Shooter game.
For the simple explosion prefabs that aren’t tied to a gameobject’s animator I just attached an Audio Source component and dropped in the audio clip and made sure the Play On Awake box is checked. Now when the explosion is instantiated it will play the sfx instantly.
For the sfx when the Player fires a laser or explodes I attached an Audio Source component to the Player. Inside the player script I added variables for AudioSource and AudioClip and serialized the field for the AudioClip so that it can be dropped into the inspector.
Inside of my player’s damage method I play the explosion sound before I destroy the player gameobject using the reference to the AudioSource and passing in the explosion AudioClip to PlayOneShot
Inside my FireLaser() method I play the laser sfx the same way.
For my powerups I need an AudioSource that doesn’t get destroyed or disabled as soon as the powerup is collected so I have an Audio_Manager empty gameobject in my hierarchy with a Powerup empty gameobject childed to it with an AudioSource component attached. In my AudioManager script I have a reference to the Powerups AudioSource and a PlayPowerUpSound method that can play the AudioClip that is passed from the individual powerup. Doing it this way I can attach a different audioclip to each powerup if I want and use the same code for all of them.
I have it pass the powerupID too but this isn’t needed for sound, it’s simply so I can use the same Action for anything that needs to know when a Powerup has been collected that does need to know the powerupID.
Inside the powerup script I allow for an audioclip to be attached. I use an Action to pass it to the AudioManager, which the AudioManager PlayPowerupSound method subscribes to.
With my enemies I do it the same way as my player and play the sound before destroying or disabling the enemy.