How to Play Sound Effects in Unity

Siddhant Thakur
Nerd For Tech
Published in
3 min readMay 7, 2021

--

In the previous article, we saw how to work with Audio Sources to play an audio clip. This article builds upon it by adding intricate control over when and which sounds to play.

Objective : Add interactive sound effects like Laser, Explosion and Power-up sounds.

Let us start by creating an Audio Source component for each of our given sound effects.

Note : Make sure to toggle Off Play On Awake, as our goal is to play the audio when we want it to play and not upon immediately when the scene is loaded (basically have manual control).

Laser Audio Source :

Explosion Audio Source:

Power-up Audio Source:

With this we have all the audio sources set up. Now lets get woking on the behavior aspect.

Behavior of the above mentioned sound effects :

For LaserAudio we want the sound effect to play when the Player fires a laser. We want the Power-Up sound to play when the Player picks up a power-up. As for the Explosion sound we wish for it to play whenever an explosion occurs.

To do this we first have to capture the reference of these objects, which can be done by doing the following,

Two ways to reference the components, GameObject.Find() and through the Inspector.

I prefer to directly assign the components through the Inspector panel by making the variables SerializeFields, as its more efficient in this scenario (Note: Using GameObject.Find() has it’s own merits).

I’ve also made it an habit to null reference components, which can be done by doing the following,

You can do the same for the other two variables as well.

With this we now have access to all the audio sources, now all we have to do is code the behavior of playing the sound.

Play Laser Audio :

To play the Audio all I have to do is,

AudioSourceGameObject.Play()

And since I want the audio to play when the Player Fires the laser, its going to be added into the FireLaser().

Play Power-up Audio :

The audio is to be played when the Player picks a Power-up,

Player Behavior Scripts

Public method as this will be referenced in the Power-up behavior script.

PowerUp behavior Script

Play Explosion Audio :

Similar to the Power-up audio,

Player Behavior Script

Public as I want other behavior scripts to be able to access this method. In this case the audio is to be played when the Laser comes in contact with the Enemy or when the Player comes in contact with the Enemy

Enemy Behavior Script

With this we now have sound effects in our game, and trust me it makes the game feel soo much better.

Thank you for reading. More to come!!!

--

--

Siddhant Thakur
Nerd For Tech

Aspiring Game Developer with experience in the field of Machine Learning.