Getting Started with Unity (Part 10: Background Audio & Sound Effects)

Sound = Immersion. There is no getting around it, game audio is often the best tool a game maker has for pulling a user into their universe. From ambient background sounds to effects when certain events play out, learning how to implement audio effectively in Unity is a critical skill. Let’s dig in!

Fortunately adding audio into your Unity game is a relatively straightforward process once you have your audio clips. The Main Camera by default has an audio listener which can pick up the various audio souces you set up for your game. These audio sources can be designed to either trigger and play from a specific location (think of a radio you walk past in a 3D game) or the audio can play globally and be heard everywhere such as with background music.

Let’s set up background music first. First, like our UI, Spawn, and Game managers, it will be helpful to have an AudioManager game object which will hold all of our audio logic. Inside this object, we create another empty game object for “Background Music” onto which we add an “Audio Source” component. The Audio Source component holds a clip to play as well as the instructions for playback:

For something like background music, which begins as soon as the game begins and loops for the entire duration, setup is a simple as adding the music clip to our audio source “AudioClip” box and checking “Play on Awake” and “Loop”. All set! Your background music will now play for the duration of the runtime of your scene.

To add a sound effect, we go through the same setup process to add an empty object to our AudioManager container and name it for the audio clip it will play — in this case “Laser Shot”. Now in our code, we can reference the laser audio source and add a command line to play our audio source whenever the laser is fired.

We can add similar effects such as playing an explosion sound when our enemies collide with the player or a laser:

Now whenever an enemy is hit by the laser or the player an explosion sound will play. This makes our combat setup feel much more satisfying.

Finally, we add the same logic to our power up script so that any of the boost collisions will trigger their respective audio as well.

All done! The background audio and sound effects add a ton of flavor to our game and really pull it all together. We’re almost ready to ship, so let’s cover how to “Build” your game before publishing. See ya there!

Unity Developer from Los Angeles, CA