Day 31: How to Play Sound Effects in Unity

Objective: Add sound effect when firing the laser and collecting power ups.

Yesterday we talked about creating a looping background music, today will be about sound effects.

We will need to get a reference to the audio clips for firing laser and powerup pick up. We will do the laser on the player script and powerup on the powerup script. After creating a serialize field reference. Go back into Unity and assign the clips to those references.

We got a reference to the Audio source. For the audio source we will need to assign it in the start with getcomponent. Always good to null check it as well.

Now that we have an audio source reference and clips, it’s time to play the clips when needed.

For the Laser, every time the player hits the space bar we need to play the sound effect. We’ll add it in the firing function we created earlier. We need to assign the correct clip to the audio source clip. After it’s been assigned use the audio source to play it.

Since the laser is done we will move over to the powerup script. Same thing will be done, get a reference to the audio and to the audio source. We’ll null check this audio source as well.

In the OnTriggerEnter, after we check to see if it’s the player we’ll play the clip.

Now we have some sound effects in the game!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tyler Smallwood

Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer