Introduction to Unity Sound

Adding sounds to your game is just as important as developing amazing shaders. In this tutorial, you’ll learn the basics of sound development in Unity by chucking animals into a barn.

3/5 1 Rating · Leave a Rating

Version

  • C# 3.5, Unity
 
Please note, this is a STATIC archive of website www.raywenderlich.com from 08 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Update note: Anthony Uccello updated this tutorial for Unity 2018. He also wrote the original.

Creating the visual elements of a game is only half of the work. Once you have your monsters in place, and you have primed all your catapults to fire, a colossal battle may appear underwhelming when the greatest of explosions fail to produce even the tiniest whisper.

But when you add sounds to your game — even terrible ones at that — you may be shocked to discover the depth that they provide. Throw in some awesome sounds and you may discover an entirely new game.

Adding sound via code isn’t difficult, but Unity, which has an easy-to-use visual editor and works with a wide range of audio file formats, makes it even simpler. This tutorial will show you how to add sounds to the game Barn Blaster, via the Unity editor and added code. If you’re looking to add sounds to your next game, this tutorial is a great starting point!

In this tutorial, you’ll:

  • Learn the difference between AudioClips and AudioSources.
  • Discover how to configure various properties of 3D sounds.
  • Programmatically play sounds.
  • Learn to maybe, just maybe, throw a pig into a barn.

This is a beginner-level tutorial, but you should be familiar with Unity’s interface. If you are new to Unity or need a refresher on the basic concepts, check out our Introduction to Unity tutorial.

Note: You will need to have Blender installed in order to open the project; get it free here.

Getting Started

You can download the materials for the project using the Download Materials button at the top or bottom of this tutorial. Open the project in Unity (minimum version 2018.2.10f1).

To start off with, open the Main scene in the Assets ▸ RW ▸ Scenes folder and click the Play button.

Introduction to Unity Sound

You’ll see a bunch of tractors driving back and forth in front of a red barn. When you press the Spacebar key, a farm animal launches into the air. The goal of the game is to land the animal in the barn without it getting hit by a tractor. If the animal gets hit by a tractor, it dies; if it makes it into the barn, it’s a goal!

Right now, of course, it’s totally silent — not a moo to be heard! You’ll bring the game to life with sound.

Adding Your First Sound Effects

The game is set up to launch a random animal: a cow, pig or sheep. Each one will play a different sound, so your first task is add the sound effect of the animal being launched.

The project has already been set up with prefabs for each animal. In the Project window, open the Assets ▸ RW ▸ Prefabs window and select the cow prefab.

Note: Never heard of a prefab? Check out our Introduction to Unity tutorial to get up to speed.

Introduction to Unity Sound

The first thing this prefab needs is an AudioSource component to play sound. In the Inspector, click the Add Component button and type in Audio Source. Then, select the Audio Source option that appears.

Introduction to Unity Sound

The cow prefab can now play audio, but it needs an AudioClip to play. Currently, the AudioClip on the component you added is empty.

Introduction to Unity Sound

You may be wondering: what exactly is an AudioSource? How does it differ from an AudioClip? You can assume the functions by their names, but assuming can be a dangerous thing — especially with flying livestock on the line — so you’ll need to cover some basics.

How Sound Effects Work in Unity

To play sounds in Unity, you use an AudioSource and an AudioClip.

An AudioSource is what will actually play the sound in 2D or 3D space. In 3D space, the sound’s volume can vary based on how far the AudioSource is from the object listening to it (the AudioListener, which, in this game, is on the camera).

You can set an AudioSource to play sound in 2D space, which means it will play at a consistent volume regardless of the distance from the AudioListener.

An AudioClip is the actual audio file that the AudioSource will play.

One important thing to note is that the AudioSource is a component. That means it’s an object that inherits from Unity’s MonoBehaviour class and can be attached directly to any Unity GameObject.

The AudioClip is a variable that can be set on the AudioSource (i.e., each AudioSource will have one AudioClip). You can attach components through the Unity editor and through code, though this tutorial only uses the editor.

A key part of playing sounds is setting up triggers for AudioSources to play. A trigger is just that: A condition that causes the AudioSource to play.

In this tutorial, you will edit code that has been pre-configured to contain only what you need for the audio-playing portions; behind the scenes is the code that uses Unity’s physics engine.

Note: If you are interested in learning how these physics triggers work, check out Unity’s Physics System.

Adding AudioClips

Open the Assets ▸ RW ▸ Sounds folder in the Project window and find the moo sound file. With the cow prefab still highlighted in the Inspector, drag the moo sound file onto the AudioClip.

Make sure that Play On Awake is enabled.

This means that the sound file will play as soon as the object is created, which is exactly what you want. When the animal is launched toward the barn, it will let out an animal roar — or moo, in this case!

As a challenge, do the same thing for the Sheep and Pig prefabs.

Need help? Just open the spoiler below to find out how.

[spoiler]

  1. Click on the sheep prefab. In the Inspector, click the Add Component button. Select the AudioSource component in the Audio category.
  2. Drag the baa sound file to the AudioClip field.
  3. Make sure the Play On Awake box is checked.
  4. Click on the Pig prefab. In the Inspector, click the Add Component button. Select the AudioSource component in the Audio category.
  5. Drag the oink sound file to the AudioClip field.
  6. Make sure that the Play On Awake box is checked.

[/spoiler]

At this point, all three animal prefabs have their voices added. To test it out, enter Play mode and press Spacebar to launch an animal. You should hear each animal playing its respective sound as it flies towards the barn.

moo

Oinks and moos and baas — oh, my!

Sound Not Playing?

The AudioSource can play a wide variety of file formats, including the common .mp3 and .wav formats. If you ever find that your sound file is not playing, first check here to see if the file format is supported.

Note: When choosing a sound format to use, you should prefer a lossless format such as .ogg or .wav.

In some cases, Unity will encode sound files into formats such as .mp3 to take advantage of certain hardware decoding. In cases in which you supplied an .mp3 audio file, those .mp3 files will be re-encoded, resulting in additional quality loss.

Since this tutorial was prepared ahead of time, the file formats should be fine. So if the sounds aren’t playing, check the following:

  1. Is the volume set too low? Check the volume level on each of AudioSources.
  2. Is the AudioSource component disabled? If the component is disabled, it won’t play the sound.
  3. Is Play On Awake toggled? You won’t always want this on but, if you expect a sound to play as soon as the object is created, check that this is toggled on. It will play at the same frame the object is created.

Polishing Sound

The game is coming along great so far — all the animals are making their sounds as they fly towards the barn. But a few things are still missing:

  • The tractors aren’t making any sound.
  • There’s no success sound when an animal makes it to the barn.
  • There is no death sound if an animal hits a tractor.

Adding these sounds will give this game this game some real polish.

Adding Tractor Sounds

To add a buzzing sound to the tractors as they move back and forth, first, hold Control (on PC) or Command (on Mac), and click on all three tractors in the Hierarchy. Batch-add an AudioSource, then add the tractor sound clip just like you did with the animal sounds. Make sure Play On Awake is checked.

With all the tractors hooked up with sound, click the Play button.

It’s great the tractors have sound, but with all three playing at the same time it’s hard to distinguish between them. Plus, it’s really loud.

As mentioned earlier, 3D sounds can play with a decrease in volume the farther away the AudioListener (in this game, it’s on the camera) is from the AudioSource. Adding a falloff effect (so that the farther the tractors are from the camera, the quieter they are) will make things sound a lot better.

Click on tractor in the Hierarchy; in the Inspector, look at the AudioSource component. There will be a drop-down area called 3D Sound Settings. Here, you can set the Doppler Level, the Rolloff and the Distance variables.

The Doppler Level is exactly what it sounds like: sound intensity that varies to mimic the Doppler effect. The Rolloff Level is how much the volume quiets down the farther its source is from the AudioListener.

This is the closest tractor to the player, so its sound falloff should be more dramatic than the back two. Set the Volume Rolloff to Linear Rolloff, which will make the effects more pronounced. Next, set the Min Distance to 1 and the Max Distance to 9. Set the Doppler Level to 0.68.

This will make the front tractor sound loud as it approaches the middle of the screen (as it moves closer to the listener on the camera) and quieter as it moves off screen. Click Play to see this for yourself.

For the back two tractors, their sounds should be more like background noise; only the front tractor should have the exaggerated sounds.

To turn down the intensity of the back tractors:

  1. Start by selecting tractor2 in the Hierarchy.
  2. Set the Volume Rolloff to Linear Rolloff.
  3. Then, set the Min Distance to 1 and the Max Distance to 30.
  4. Set the Doppler Level to 0.68.
  5. Next, select tractor3 in the Hierarchy and set the Volume Rolloff to Linear Rolloff.
  6. Set the Min Distance to 1 and the Max Distance to 50. Set the Doppler Level to 0.68.

Click Play and listen to the different sound levels of the tractors as they move back and forth.

The tractors are way too loud, especially with three of them playing at once. Set the Volume slider on their AudioSource to 0.4.

If you play the game for more than 40 seconds, you’ll notice that the tractor sounds cut out. That’s because their AudioSource hasn’t been set to loop. To change this, click the Loop box for each tractor’s AudioComponent.

Adding Hit Sounds

When the animals hit a tractor, unfortunately, they get clobbered by it. What’s even more unfortunate is that there is currently no sound when that happens! As mentioned earlier, the tractors are using the Unity physics engine and listening for collisions with the animals. When an animal collides with a tractor, it tells the animal to die — that’s when the sound needs to play.

First, you will need to attach the AudioClip of the death sound to the Tractor component. To do this:

  1. Hold Control (on PC) or Command (on Mac). Then click on the three tractors in the Hierarchy.
  2. Select the three tractor GameObjects and click the dot next to the Death Sound field of the Tractor component in the Inspector.
  3. Next, select the death sound file from the Select Audio Clip pop-up window shown below.

To code in the animal death sound, start by double-clicking on the Tractor C# script to open it in your editor (found in the Assets \ RW \ Scripts folder). Before the closing brace of the if statement, add the following code:

audioSource.PlayOneShot(deathSound);

The final result should look like this:

void OnCollisionEnter(Collision col) 
{
    if (col.gameObject.GetComponent<Animal>() && !col.gameObject.GetComponent<Animal>().isDead) 
    {
        Destroy(col.gameObject);
        audioSource.PlayOneShot(deathSound);
    }
}

Press Control-S (on PC) or Command-S (on Mac) to save the script.

PlayOneShot() plays the sound once. You are passing in the sound that you added to the tractor and then playing it once from the tractor. The reason the tractor (rather than the animal) should play the sound is that, when the animal is hit by the tractor, the literal GameObject that was the animal is deleted. Since it no longer exists, the animal can’t play a sound. You could turn the mesh off and play the sound from the animal that way, but that is more complicated.

The benefit of using PlayOneShot() is that the sound will play to completion even if PlayOneShot() is called again. If this were not the case, the animal sounds would cut each other off, sounding jerky to the user.

Click Play and exercise your darker side by intentionally launching animals into the tractors instead of aiming for the safety of the barn. You should hear a “squish” sound as they collide with the tractor.

squish

Adding Celebration Sounds

The only missing sound at this point is the success sound when an animal makes it to the barn.

To add those:

  1. Start by clicking on the barn object in the Hierarchy.
  2. In the Inspector, add an AudioSource component to it.
  3. Then, drag the win sound from Assets ▸ RW ▸ Sounds to the AudioClip field.
  4. This time, make sure Play On Awake is turned off. This sound will only be played if an animal makes to the barn.
  5. Double-click on the Barn script in Assets ▸ RW ▸ Scripts.
  6. Underneath the opening brace of the if statement, add the following:
    if(col.gameObject.GetComponent<Animal>())

    It should look like this:

    	
    void OnCollisionEnter(Collision col)
    {
        if(col.gameObject.GetComponent<Animal>())
        {
            GetComponent<AudioSource>().Play();
            Destroy(col.gameObject);
        }
    }
    

    This tells the barn that, when an animal collides with it, it should get the AudioSource component and play it. Save your changes, then click play and launch animals into the barn. A success sound will now play when the animal makes it to the barn.

Success!

Finishing Touches: Varying Sound Effects

There’s one last bit of polish you can add for very little effort. Hearing the exact same sound over and over is annoying. To keep sounds fresher and less irritating, code in some variance to the pitch.

Open the Animal C# script in the Scripts folder. Add the following just under public bool isDead = false;

void Start()
{
    AudioSource audioSource = GetComponent<AudioSource>();
    audioSource.pitch = Random.Range(0.8f, 1.5f);
    audioSource.Play();
}
 

This code fetches the AudioSource component and sets the pitch variable to a random value between 0.8 and 1.5. Now, click Play and launch the animals. Their animal sounds will vary each time. Pretty cool, right?

Where to Go From Here?

Great job adding your first sound effects to a Unity game! Now, your animals can happily moo, oink and baa their way into the barn — unless they get hit by a tractor, of course.

If you ran into any issues, open the final project to compare against using the Download Materials button at the top or bottom of this tutorial.

For more fun, try adding different pitches to each of the tractors, to the success sound that plays when an animal makes it to the barn, and to the death sounds. You can also try adding different animal sounds and a unique death sound for each animal (although that will require a little more coding, along with finding more audio files).

To learn more about Unity’s sound engine, check out Unity’s Live Training on Adding Sounds Effects to Your Game. Also, check out the AudioSource and AudioClip Unity documentation.

Stay tuned for future Unity tutorials! Feel free to leave comments below.

Average Rating

3/5

Add a rating for this content

1 rating

Contributors

Comments