Gaming in Unity

17. Unity 2D Game 13 - Audio


In this final guide, we will add Background Music and Sound Effects!

Step 1 - Background Music

Create an empty GameObject, name it BackgroundMusic.

Add an Audio Source component.

Drag and drop an audio clip into the AudioClip slot.

Check the Loop option.

Make sure Spatial Blend is 0.


Enter Play Mode and your background music should now play!

Step 2 - Adding Audio to Character

Click on SpriteCharacter and add an Audio Source component.

Open SpriteController script and add an AudioSource variable.

Retrieve this in void Start( ):


Add a function for playing a sound:


Open the HealthCollectible script and add an AudioClip called collectedClip.

Call the PlaySound function of SpriteController.


Drag and drop Collectible.wav onto the AudioClip slot of the Script on Heart.


You should now hear the Collectible sound any time you pick up a Heart!

You can use this step to add more sounds such as a throwing sound or getting hit sound.

Open SpriteController Script, declare AudioClips and then play them at appropriate points in the code.



Don't forget to add the clips to the slots in the Inspector.


Step 3 - Spatialization

Open the Robot Prefab and add an Audio Source component.

Set the AudioClip to Robot Walking.wav

Enable Loop.

Set the Spatial Blend slider to 1.

Set Max Distance to 10.

This will make Robot Walking play when you're close to the Robot and then gradually get quieter when further away.


Select the Main Camera and create an empty Child GameObject. Call it Listener.

Add an AudioListener component to Listener.

Set Position to X = 0, Y = 0, Z = 10.


Remove the Audio Listener component from Main Camera.


Robot's walking sound will now change in volume depending on distance from CharacterSprite!

Created by: David Corish