How to Play Sound Effects in Unity

Blake Zoeckler
2 min readMay 19, 2021

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.

Create this audio source component for the player object in the scene.

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.

New variables in the Player script

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.

Also in the Player script.

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.

Attaching the laser_shot sound clip to the new variable.

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

--

--

Blake Zoeckler

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