How To Play Sound Effects In Unity (Game Dev Day 29)

Objective: Implement sound to our game in Unity.

Let’s start off with background music that will play constantly.

Create a new empty Game Object and name it something appropriate (Audio_Manager).

Next, create a child empty Game Object and also give it a name (Background)

On the Background empty Game Object, add an Audio Source component in the Inspector

Make sure this is your Background Game Object.

Drag your appropriate audio clip into the AudioClip slot, and make sure “Play On Awake” and “Loop” are turned on.

Go ahead and test it, you should have constant background music that will loop endlessly.

If we want sound to play at specific times (like when we fire our laser or an enemy dies) we have to code some logic for the game to understand.

We’ll do the laser as an example.

The laser is instantiated by the Player.cs which is attached to the Player Game Object.

Let’s add a variable to the script so we can link the sound effect in the Inspector.

Serialize the field so we can drag in the sound clip we want.

Go ahead and drag your desired sound effect into the new slot on the

Player (Script) component of the Player Game Object.

Mine is at the bottom (Laser Sound Clip).

Next, add an Audio Source to the Player Game Object from the Inspector window.

Make sure you are editing you Player Game Object.

Drag in the same sound effect for the AudioClip option.

We need to be able to GetComponent from this Audio Source, so go back into the Player.cs script and let’s add a handle so we can call this component.

Then, in void Start we need to GetComponent:

Finally, we need to set up when the sound effect should play. For this sound, it should play when the player fires a laser.

We are just adding the _audioSource.Play();

So now when we instantiate either the triple shot or the regular laser, the audio clip we selected will play right after.

This same method can be used for the explosions, for picking up powerups, taking damage, etc.

Unity Developer