Adding Sound in Unity

Harvey Limbo
3 min readApr 12, 2021

--

For today’s article, I’ll be going over how I added background music and sound effects to the Space Shooter game I’m developing above.

Prerequisites

  • Game Scene must have an Audio Listener component attached to a game-object. This would be attached to the Main Camera game-object by default when a new scene is created.

Sounds to Add

  • Background music
  • Player laser SFX
  • Power-up pick up SFX
  • Enemy/Asteroid Destruction SFX

Background Music

To add background music, I added a new game object into the scene and attached an Audio Source component:

I ticked the Play On Awake and Loop options to true to allow the background music to immediately play when the game first starts and to allow the music to continuously play on repeat. For the AudioClip section, I added in a .wav file. Based on my own research, the list of supported file formats for audio can be found here where .wav is one of the supported file formats.

Player Laser SFX

I add the Laser Fire audio clip to the Unity Editor and in the Player script, I use the PlayOneShot(AudioClip clip) function from the AudioSource component to play the laser shot sound effect:

Make sure to attach the AudioSource component to your game object

This will play the laser sound effect every time the player presses the space key and as long as their fire rate is not on cool-down.

Power-up Pick up SFX

Similarly, in the Player script, I add an audio clip reference to the power up pick up sound effect:

The .tag variable comes from Unity’s Tag Manager where all Power-ups are tagged with the “Powerup” string:

Enemy/Asteroid Destruction SFX

For this last section, I won’t include how I added Asteroid destruction sound effect since that is similar to how enemy destruction sound effect implementation is built.

Add Audio Source component to Enemy game object

To add Enemy destruction SFX, I implemented the following code below:

A reference to the coroutine named delayDestructionRef is added in this script because we don’t want the Audio Source to play the enemy destruction audio clip more than once. It also ensures that the coroutine DelayDestruction does not get run more than once.

The DelayDestruction coroutine’s responsibility is to delay the destruction of the enemy to allow the explosion animation clip to finish to completion AND to allow the explosion audio clip to play. If they delay in destroying the enemy is not added here, the audio source would not play the clip as the game object would be immediately destroyed after the current frame it was requested to be destroyed in.

Thanks for reading :)

--

--