How to Play Sound Effects in Unity

Unlike background music, sound effects will only play when something happens to make the sound. This example will add the laser sound effect when the player fires the laser. To start you need to add an audio source to the player so that it can play sounds. Don’t assign an audio clip to the audio source. This will be done in the script so that the audio source can use different audio clips.

Next, in the Player script create two variables. One for the Audio Source and one for the audio clip you will play.

private AudioSource _audioSource;
[SerializeField] private AudioClip _laserAudioClip;

In the Unity editor assign your laser sound effect to the laser audio clip variable. Then, back in the Start function use GetComponent to assign the audio source. And don’t forget to double check that it was assigned. Here is also a good point to assign the laser audio clip to the audio sources clip.

_audioSource = GetComponent<AudioSource>();
if (_audioSource == null)
{
Debug.LogError("The Audio Source on the Player is NULL.");
}
else
{
_audioSource.clip = _laserAudioClip;
}

Last, in the function where the laser is fired you can now call Play from the audio source and it will play the clip you have assigned to it.

_audioSource.Play();

You can use this same method to do all kinds of sound effects.

Good Luck Adventurer!

-Chris