Hear the BOOM!
How to Play Sound Effects in Unity
Last time we looked at how to add background music to our game to increase our player’s immersion. Now let's add sound effects! We’re going to add a laser sound when ever the player fires a laser.
Adding a Laser Sound
For this project we’ve been provided with a laser sound, so we’ll use that. If we had not been provided with the sound we could have gone to the Unity Asset store or another source like freesound.org.
We’re going to have the Player object be responsible for playing the laser sound when the user presses the fire key. To start we are going to need add an AudioSource component to the Player object in Unity. We’ll want to make sure that Play On Awake and Loop are both unchecked. Unlike our background music we don’t need to assign our audio clip to this AudioSource because we are going to assign it through code when we play it.
Next we will need a reference to the sound we want to play. We will store this in a serialized AudioClip field. We will also need to store a reference to the AudioSource component attached to the Player GameObject, so we will create a private variable for that as well.
We’re going to go ahead and cache and null check our AudioSource using GetComponent();
Now, after null checking our audio source again, we can use the PlayOneShot method of the cached audio source to play the AudioClip that we set through the inspector.
This leaves us with the following in our Damage Method
Next we’ll add the explosion sound to our enemies when they die either by colliding with a laser or with the player. Just like the laser sounds we will need to have a reference to an AudioClip in our Enemy script. Unlike our player, this time we’re not going to attach an AudioSource to our enemy (though we could have used the same technique as above).
This time we’ll use the static method PlayClipAtPoint from the AudioSource class to play our clip when the enemy is destroyed.
Leaving us with
Now our player will hear lasers and explosions accordingly when these events happen in our game! Next time, we’ll look at building and testing our game! If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.