How to Play Sound Effects in Unity
Is a Game Really a Game without Sound Effects?
Creating Sound Effects for the Laser
When the Player fires his laser at the enemies, there should be some sort of “spacey” laser sound effect. Without it, the game would dull and boring. Let’s dive right into what we have to do to create a cool laser sound effect in our game.
At first you might think we would go to the Laser script and add some sort of “Audio” code, if you will, to give the laser the sound effect. However, we actually need to head over to the Player script for this. Since the player is the one firing the laser, we want the audio to play as soon as the [Spacebar] key is pressed, and a laser is fired.
We need to let Unity know what audio clip we are wanting to play. This is done by creating a variable to store the clip, and a variable to store the audio source. Since we do not have an Audio Source component, we need to add one. Follow the steps below for this.
- Select Player in the Hierarchy.
- In the Inspector, scroll to the bottom, and click Add Component.
- Type “Audio Source”, and select it when you see it show up.
In the Audio Source component, remove the tick (checkmark) from the box for “Play On Awake”.
Now let’s hop into the Player script so we can add the variables I mentioned earlier. In the Player script, we want to add the following code.
private AudioClip _laserSoundClip;
private AudioSource _audioSource;
Now you will be able to see the Laser Sound Clip box in the Player (Script) within the Inspector. Drag your audio clip into this box.
Next, we will be adding the code that let’s Unity get the Audio Source. We do it this way, instead of just dragging it into the Inspector, for two reasons. First, this will ensure that AudioSource is not NULL. Second, we would not have to reassign it if Unity were to crash.
Type the code just as you see it in the Player script GIF below.
To assign the clip, we just need to add a little more code. We already have
“if (_audioSource ==null)”, followed by the code to display a message if it IS null. Now we need to write the code that tells us what to do if _audioSource is not null. The GIF below will show what this needs to be.
Within the Player script, locate the void FireLaser() method. We now need to let Unity know that we want to play the audio clip when the laser is fired. Type the code below, within the void FireLaser() method.
Save your scripts, and save your game. Then, test it out to hear your new audio effect for the Laser.
There is such a huge difference between having audio for the lasers, and not having audio for them. Play the game with the audio, then play it again with your speakers or headphones turned off. It is amazing how much better the game is with sound effects.
I would like to thank all of you who took the time to read my article.