Gaming in Unity

17. Unity 2D Game 13 - Audio

(../img/unity-17-2d-game-13-audio/2d-game-13-audio-header.png)

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.

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-1.jpg)

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( ):

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-2.jpg)

Add a function for playing a sound:

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-2-2.jpg)

Open the HealthCollectible script and add an AudioClip called collectedClip.

Call the PlaySound function of SpriteController.

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-2-3.jpg)

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

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-2-4.jpg)

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.

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-2-5.jpg)

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-2-6.jpg)

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

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-2-7.jpg)

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.

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-3.jpg)

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.

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-3-2.jpg)

Remove the Audio Listener component from Main Camera.

(../img/unity-17-2d-game-13-audio/2d-game-audio-step-3-3.jpg)

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

Created by: David Corish