How to Play Sound Effects in Unity

Last time we created some music, but now it’s time to add a sound effect for the laser! There’s a major difference between sound effects and music. Music should be playing constantly, so we can set it up and let it loop, without needing to code anything. However, sound effects should only be played at certain times, so we should control it using code.

The player object will be in charge of this, since that’s the entity currently in charge of shooting lasers. Let’s give that player an Audio Source component so it can make some noise.

Now we should adjust the Player class to allow this source to play the correct sound. Not only do we want a handle on the AudioSource, but we also need to keep track of the AudioClip that we want to play.

The laser sound should be played when the laser is fired, so naturally we add code to the FireLaser method. We can set the audio source clip to the sound effect we want, and then tell it to play that clip. This is the best practice for playing sound, since it allows us to change out the laser sound for something else while the game is running. Maybe a future powerup could allow the player to shoot missiles, and that would require us to change the sound to something else.

Before playing the sound, we could also code in additional effects as necessary, like changing the volume.

Now we just need to assign that new _audioSource variable to something in the inspector.

All done! Now we get nice arcade sound effects when shooting.



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
Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.