神刀安全网

Introduction to Unity Sound

Introduction to Unity Sound

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 of a 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’ll 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 by using the Unity editor and by adding code, so if you are 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

First, download the source project: . Open the project in Unity and hit play.

Introduction to Unity Sound

You’ll see a bunch of tractors driving back and forth in front of a red barn. When you hit thespace bar, a farm animal launches into the air. The goal of the game is to land the animal in the barn without 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 the prefabs (object templates) for each animal. In the Project tab, click on the Assets/Prefabs folder 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. Click the Add Component button and type in AudioSource , then select the only 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

Some of 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 let’s cover some basics.

How Sound Effects Work in Unity

To play sound 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.

The AudioClip is the actual audio file the AudioSource will play.

Introduction to Unity Sound

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 member variable that is found 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 which causes the AudioSource to play.

In this tutorial you will be editing code which has been pre-configured to only need you to code in the audio-playing portions, but behind the scenes is 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

Click on the Assets/Sounds folder in the Project view and find the moo sound file. With the cow prefab still highlighted in the Inspector , drag the moo sound file onto the AudioClip .

Introduction to Unity Sound

Make sure there is a check mark in the the Play On Awake box.

Introduction to Unity Sound

This means 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 to find out how.

Solution Inside Select Show

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

Introduction to Unity Sound

Oinks and moos and baas—oh my!

Sound Not Playing?

The AudioSource can play a wide variety of file formats, including the most 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 select a lossless format such as ogg or wav .

In some cases, sound files will be encoded into formats such as mp3 to take advantage of certain hardware decoding. In cases where mp3 is used, 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. Introduction to Unity Sound

  3. Is the AudioSource component disabled? If the component is disabled, it won’t play the sound.
  4. 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.

Sound Polish

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.

Tractor Sounds

To add a buzzing sound to the tractors as they move back and forth, first hold Control on Windows and 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.

Introduction to Unity Sound

With all the tractors hooked up with sound, hit the play button.

Introduction to Unity Sound

Hmmm … 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 further the AudioListener (in this game it’s on the camera) is from the AudioSource. Adding a falloff effect (so that the further 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 varies to mimic the Doppler effect . The Rolloff Level is how much the volume quiets down the further it 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, and set the Min Distance to 1 and the Max Distance to 9 . Set the Doppler Level to 0.68 .

Introduction to Unity Sound

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. Hit play to see this for yourself.

Introduction to Unity Sound

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, start by selecting tractor2 in the Hierarchy. Set the Volume Rolloff to Linear Rolloff , then set the Min Distance to 1 and the Max Distance to 30 . Set the Doppler Level to 0.68 . Next, select tractor3 in the Hierarchy and set the Volume Rolloff to Linear Rolloff . Set the Min Distance to 1 and the Max Distance to 50 . Set the Doppler Level to 0.68 .

Hit play and listen to the different sound levels of the tractors as they move back and forth.

Introduction to Unity Sound

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

If you play the game for more than 40 seconds, you’ll notice 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 .

Hit Sounds

When the animals hit a tractor, they unfortunately 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 an AudioClip of the death sound to the Tractor component. To do this, hold Control on Windows or Command on Mac and click on the three tractors in the Hierarchy. Click on the Sounds folder in Assets and drag the death file to the Death Sound field of the Tractor component:

Introduction to Unity Sound

To code in the animal death sound, start by double-clicking on the Tractor C# script to open it in your editor. 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);   } }

Hit Control-S on Windows or Command-S on Mac to save the script.

PlayOneShot() plays the sound once. You are passing in the sound 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 user.

Hit 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.

Introduction to Unity Sound

Celebration Sounds

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

To add that, start by clicking on the barn object in the Hierarchy. In the Inspector, add an AudioSource component to it, then drag the win sound from Assets/Sounds to the AudioClip field. This time, make sure Play On Awake is turned off. This sound will only be played if an animal makes to the barn.

Double-click on the Barn script in Assets/Scripts . 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 hit play and launch animals into the barn. A success sound will now play when the animal makes it to the barn.

Introduction to Unity Sound

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 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 hit play and launch the animals. Their animal sounds will vary each time. Pretty cool, right?

Introduction to Unity Sound

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, download the completed project: Barn Blaster – Complete Project

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 Sound 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, or join the conversation in our forums .

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Introduction to Unity Sound

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址