Playing Sound Effects in Unity

Did You Hear That?

James Hills
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”.
Adding Audio Source to Player

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.
Adding Code to Handle Audio Source and AudioClip
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.
Add ‘laser_shot’ Audio Clip in the Inspector

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.

Thank you for reading my article. If you liked what you read, please follow me on Medium for the next update to this 2D Space Shooter game.

--

--

James Hills

I am a married father of 5 children. I decided at 13 years of age that I was going to become a Software Developer.