Playing Sound Effects in Unity
Did You Hear That?
3 min readMay 31, 2022
You have to have sound effects in your game, or it just really isn’t a game. I’ve added some really great sound effects and I’m going to show you how I did that. I will use my Laser as the example.
Every time I hit the space key, a laser is fired from the spaceship. I want to hear that laser firing.
The first thing I had to do was add an “Audio Source” to the “Player” game object.
- Select “Player” in the Hierarchy panel, click on the “Add Component” button in the Inspector panel, add the “Audio Source” component, and remove the checkmark from “Play on Awake”.
This will take some code to get it working.
- Inside the “Player” script, add some code to allow access to the AudioClip and AudioSource component.
Note: It's better practice to get the AudioSource Component, rather than use it in the Inspector. This ensures the component is never NULL and if Unity were to crash, we wouldn't have to reassign it in the Inspector. For these reasons, we don't use the [SerializeField] attribute.
- In the “Player” script, inside the Start() method, add the code to get the AudioSource component and to check that the AudioSource isn’t NULL. If it isn’t NULL, then assign the audio clip.
- Next, with the Player object selected in the Hierarchy panel, I added the “laser_shot” audio clip in the corresponding slot in the Inspector panel.
Playing the Laser Sound
Now I want to hear the laser when I a shot is fired.
- The following code will be added to the “Player” script, inside the FireLaser() method. This will allow access to the AudioSource and allow it to play when a shot is fired.
And now I have a laser shot sound when a shot is fire.