Adventures in GameDev with GameDevHQ! Day 33:How to play sound effects in Unity.

As stated yesterday, The Audio component is the audio heart of any GameObject. If your object makes noise, it will have this component in it.

One of the options it has is ‘Play on Awake’ so as soon as an object appears and it holds this component, it will begin playing. This is pretty useful in a couple of cases. Let’s say we want to play background music in a loop. We can create an AudioManager with an AudioComponent that has the music attached to it, and loop enabled. Just place it into the scene and you have a simple music player!

Another example is attaching an audio component to the Explosion animation prefab. Place the explosion sound into it, and click PlayOnAwake (but not the loop for obvious reasons) and you have an explosion with a thunderous roar which will destroy itself in a second or two with the appropriate script. Very simple!

Sometimes though, you’ll need to have a little more control when and how the sound plays. Fortunately, Unity offers solutions for coding as well and it’s just as easy! Let’s say for example we want to add a lasershot sound every time we fire.

Just like the other day when we added the smoke to our ship, we make room in our Player for the laser audio clip:

Then you drag the laser_shot sound into the empty Laser_Clip audio slot:

Now if you were to play the laser sound, where would you put it? Of course in the Fire() method! Right below where the lasers are being instantiated, you can place this code:

And that’s all there is to it!

One more thing, if you wanted to add a powerup sound to your powerups, the powerups get destroyed as soon as they’re picked up so what can you do? Use a PlayClipAtPoint! It allows you to instantiate, play, and destroy an audioclip all at once!

You do need to give it a position in space, but you can just use your GameObjects transform position and it will play spatially wherever your object is located at meaning the player will hear the sound appropriately to the left or right of him if listening in stereo.

That’s all for now! Tomorrow we’ll go into building our game!