Signup/Sign In

Unity 3D: Adding Sound Effects to Game

Audio is quite an interesting concept to cover, not only in game design but when studying its nature in general. The way it's perceived depends on a lot of factors, which have to be taken into account when you're trying to control or use it.

Perception of audio generally involves the position of the source and how fast it's moving if it's moving at all (If you've studied Physics, you may be familiar with the Doppler Effect).

In Unity, the positioning of a source of audio is important to characterize its source. For example, we need to make sure that a gameObject playing the sound of a waterfall matches with an actual waterfall gameObject, and that the player's perception of that sound feels real. Getting louder as the player gets closer, making sure the audio panning varies as the relative position of the waterfall changes with respect to the player, and so on.

We deal with 2 main components related to Audio in Unity, they are:

  1. Audio Listener
  2. Audio Source

Let's have a look at these components.


Audio Listener

This is a component that's automatically attached to the main camera every time you create a scene. It doesn't have any properties, since its only job is to act as the point of perception. Leaving the Audio Listener as it is, is recommended.


Audio Source

This is the component that's actually responsible for playing the sound. In common development practice, it's generally a good idea to make an empty gameObject to act as the Audio Source and make it a child when you're dealing with large, complex structures, so you have a clear idea of where the Audio Source is.

Creating audio source as an invisible gameObject


The Audio Source component has quite a few properties which we can tinker around with. This includes its pitch, panning, spatial blending (We'll get to that later), and if you open the 3D Sound Settings, you will find options for adding Doppler Effects and volume rolloffs.

What interests us the most here is the AudioClip slot, however. That's where the sound effect to be played goes. Unity supports quite a few common sound formats, including .mp3 and .ogg etc.


Adding your Own Sound Effects

Until sound-supportive documents are supported, we'll have to create our own sound effects. We have made a package of a pair of small sound effects, which you can download from here.

Let's import these sound effects into our project by creating a new folder for sound effects and adding the sounds to it.

Adding sound clips in Unity


Now, since the main camera already has an Audio Listener, all we have to do is add Audio Sources to our relevant gameObjects.


Unity 3D: Adding an Audio Source

First off, we'll have a sound effect that plays when our character fires a fireball. For that, we'll simply attach an Audio Source to our character's shooter gameObject. Go to Add Component → Audio → Audio Source.

In the AudioClip slot, drag in the sound effect you want to use. If you downloaded the soundpack, drag in fire1.mp3. Now, untick the Play on Awake checkbox. This makes sure that this sound doesn't play as soon as the gameObject awakes, which in our case is as soon as the game starts.

In the tutorial Prefab Instantiation and making them move, we created a class Shooter which was instantiating a new fireball every time Spacebar was hit, let's add sound when a new fireball is fired.

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

public class Shooter : MonoBehaviour
{
    public GameObject fireball;
    private AudioSource source;
    
    void Start()
    {
        source = GetComponent<AudioSource>();
    }
    
    void Update() 
    {
        // When spacebar is hit
        if(Input.GetKeyDown(KeyCode.Space))
        {
            // instantiate the fireball object
            Instantiate(fireball,
                new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, 0),
                new Quaternion(0, 0, 0, 0));
                
            // play the sound
            source.Play();
        }
    }

}

Besides the declaration of the AudioSource variable initially, the magic happens when we call, source.Play(). This line of code makes the referenced AudioSource play the AudioClip that's loaded into its slot. It has an overloaded(variant) method as well for playing the sound effect after a certain specified delay.

Now, save this script, and simply fill in the slot in the Player's AudioSource's AudioClip slot with your sound effect. (Use fire1.mp3 if you're using our soundpack, that you just downloaded.)

Similarly, for the target, we will update the script for class TargetBehaviour used in the tutorial Detecting Collisions and attach an Audio Source to it, then use the script:

public class TargetBehaviour : MonoBehaviour
{
    private AudioSource source;
    
    void Start()
    {
        source = GetComponent<AudioSource>();
    }
    
    void onCollisionEnter2D(Collision2D col) 
    {
        // When target is hit
        if(col.gameObject.tag == "Bullet")
        {
            Debug.Log("Target was Hit!");
            
            // calling AddScore method
            ScoreBehaviour.AddScore();
            
            // play sound
            source.Play();
            
            Destroy(col.gameObject);
            Destroy(gameObject);
        }
    }

}

And fill in the AudioClip slot with your sound effect when the target gets destroyed (dead3.mp3 if you are using our soundpack). Play the game, and you can hear the sound effects when the player shoots a fireball and when it hits a target!


Unity 3D: Adding Sound Effects Summary

All in all, you have to do the following things to add an audio clip to your game:

  1. Add an AudioSource component to your gameObject, like you add a RigidBody or BoxCollider component.
  2. In the script attached to the gameObject, initialise a variable of type AudioSource
  3. In the Start() method, use GetComponent to set the AudioSource component to the AudioSource variable.
  4. When you want the sound to play, call the Play() method.