Playing Sound Effects in Unity

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.

--

--

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