Add Game Audio

In this tutorial, you will add audio such as background music and sound effects (SFX) to the Bouncy Box game. However, the same methods of adding audio can be used for any game you create.

Setup the Project



Let's start by opening up the Bouncy Box project that you created before.

You can do this by opening Unity Hub, and in the Projects section click on your Bouncy Box project.

Cannot load image

If you do not see your project in the Projects list, you can add it by clicking ADD in the top right.

In the file explorer, you can go to the directory where you saved your project, click on the project folder, then click select folder.



Add Background Music

At the moment, the game is completely silent, so let's add some sound.



Open the MainMenu scene. The first thing we need when adding audio, is an Audio Listener. This component acts as a microphone in the game. It receives input from any given Audio Source in the scene and plays sounds through the computer speakers.

It is common to add an AudioListener component to the Main Camera, since whichever GameObject you attach the AudioListener to, is the place from where you will hear sounds in 3D.

The Main Camera should already have an AudioListener component. If you do not see the component, you can add one by clicking Add Component and searching for Audio Listener.



The next component we need is an Audio Source. This component can play back Audio Clips in the scene.

You should attach an Audio Source component to any object that you want to make sounds.

The first audio we will add is some background music to the game. To do this create an Empty Game Object named BackgroundMusic, reset its Transform and add an AudioSource component to it.



On the Audio Source component, we can put any audio that we want to play in the Audio Clip field.

For the background music, you can use any sound you want. In this lesson we will use the free Blazer Rail Music Loop from dl-sounds.com. You can download the music here.

In the Unity Assets folder, create a new folder called Sounds. Then drag the downloaded music into this folder.



Now you can simply drag this audio into the Audio Clip field of Audio Source on the BackgroundMusic Game Object.

Make sure Play On Awake is checked which means the sound will automatically play as soon as the game starts. Also check Loop so that the audio will repeat on loop.



Now play the game and you should hear the music playing. However, if you click the Play button on the main menu and go to Scene01, you will notice that the music no longer plays.

This is because the BackgroundMusic Game Object is only in the main menu scene. Whenever new scenes are loaded, all the Game Objects in the previous scene get destroyed and the Game Objects in the new scene get created.

We need to make sure that the BackgroundMusic Object does not get destroyed when a new scene loads. This can easily be done via scripting, so create a new script called DontDestroy and attach it to the BackgroundMusic Game Object.



Now open the script.

Delete the Start() and Update() functions and instead add the Awake() function.

The Awake() function is similar to the Start() function except that the Awake() function always runs before the Start() function.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DontDestroy : MonoBehaviour
{
    private void Awake()
    {
        
    }
}
          

Inside the Awake() function we can simply add the DontDestroyOnLoad() and pass in this.gameObject as an argument.

This will stop the BackgroundMusic Game Object from getting destroyed when we go to a new scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DontDestroy : MonoBehaviour
{
    private void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
}
          

Now save your script, return to the Unity Editor and play the game.

When you go to Scene01, the background music will continue playing and you will notice in the hierarchy that the BackgroundMusic object is now in this scene under DontDestroyOnLoad.

If you recall from the Settings Menu lesson, we created a volume slider that can control the volume in the game. However, before this can work we need to add the Master Audio Mixer Group to the Audio Sources that we want to control the volume of.

Click on the BackgroundMusic Game Object and you will see an Output field on the Audio Source component. This field will cause the sound to be played through the Audio Mixer first before going to the Audio Listener.

Use the selector to select the Master Audio Mixer for this field.



Now test your game and make sure that the volume slider in the settings menu changes the volume of the background music.

Add Sound Effects

Now let's add some sound effects (also known as SFX) to the game



Download the three sound files below:



Now add them to the Sounds folder in your Assets.



The first sound effect we will add is for when the Box bounces i.e. whenever we press the spacebar.

Open Scene01 and on the Box object, add an AudioSource component.



Now open the BoxBehavior script.

The first thing to do is create a variable that will reference the sound we want to play when the Box bounces. Create a public AudioClip named bounceSound.

It is public so we can set the Audio Clip in the inspector.

public class BoxBehavior : MonoBehaviour
{
    public float flapForce = 80;
    public float health = 100;
    public int numCoins = 0;
    public AudioClip bounceSound;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GetComponent<Rigidbody>().AddForce(0, flapForce, 0);
        }
    }
}
          

Now we just need to play the Audio Clip with the Box's Audio Source whenever we bounce (press the spacebar).

We already have a place that checks if we press the space bar so we can just add the code in this if statement.

In the if statement, we want to get the Audio Source component and then we can use the PlayOneShot() method which takes in an Audio clip and plays it.

public class BoxBehavior : MonoBehaviour
{
    public float flapForce = 80;
    public float health = 100;
    public int numCoins = 0;
    public AudioClip bounceSound;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GetComponent<Rigidbody>().AddForce(0, flapForce, 0);
            GetComponent<AudioSource>().PlayOneShot(bounceSound);
        }
    }
}
          

Here we use the GetComponent method to get the AudioSource of this object. We then use PlayOneShot() to play the bounceSound.

Now save your script and go back into the Unity Editor. Then open the Box in the inspector and you will see the Bounce Sound AudioClip field.

Add the bounceSound asset into this field.



On the AudioSource component, uncheck Play On Awake as we are not playing the sound at the start of the game.

You will probably need to reduce the volume too, so that the sound effect is not too loud.



Now play the game and you will hear the sound every time you press the spacebar.

Once again, we can add the Master Audio Mixer to the output field on the Audio Source of the Box. This way the volume of the bounce sound will also get adjusted with the volume slider in the settings menu.



Test your game to make sure that the volume slider in the settings menu changes the volume of the bounce sound.

Finding Audio Files

There are many locations on the web where you can find audio files to use for your games.

  • Soundsnap is a professional site with a large quantity of audio that you can use if you have an account.
  • You can find music and sound effects that are free to use under the creative commons license at Freesound.org.
  • If you want to make your own 8-bit sounds for your game, you can use BFXR.
  • If you're looking for free songs to use, you can check out the NoCopyrightSounds Youtube Channel. After you have found a song you like, you can download it by removing the ube from the URL to open a site to download the file.


SFX challenge

Challenge yourself by adding more sound effects.



Add a sound effect that plays when the player collects a coin and another sound effect that plays when the player collides with a fireball.

The following steps should help you complete this challenge.
  1. Update the DamageOnCollision and CoinOnCollision scripts so that they both have public AudioClip variables.
  2. Then update the if statement in the OnTriggerEnter() method of each script so that when they collide with the player, the Audio Clip plays.

    Instead of adding an AudioSource component to the object and playing the sound with that, we will use the AudioSource of the Box to play the clip.

    This is because the coin and the fireball both get destroyed when they collide with the Box, so if they had their own AudioSource to play the sound, this would also be destroyed and the sound would not play.

    To get the audio source of the Box, we can use other.GetComponent<AudioSource>(). Also make sure this statement comes before the Game Object is destroyed with Destroy(gameObject).
  3. Here is an example of what the CoinOnCollision script should look like.

    public class CoinOnCollision : MonoBehaviour
    {
        public AudioClip coinSound;
        
        private void OnTriggerEnter(Collider other)
        {
            if (other.tag == "Player")
            {
                other.GetComponent<BoxBehavior>().numCoins += 1;
    
                print("Coins: " + other.GetComponent<BoxBehavior>().numCoins);
    
                other.GetComponent<AudioSource>().PlayOneShot(coinSound);
    
                Destroy(gameObject);
            }
        }
    }
              
  4. Add a sound file to each of the AudioClip fields in the inspector for each prefab.