How to Play Sound Effects in Unity

Pew pew pew Boom!

Tristan Engel
2 min readMay 28, 2021

--

Time has come to add in sound effects to our game.

Add Background music

The easiest of them all.
Create Gameobject
Add Component: Audio Source (Play on Awake, Loop both checked)
Drag in AudioClip

Laser Shot Sound Effect

Select Player
Add AudioSource Component to Player
Play on Awake, Loop both unchecked
Drag in AudioClip: Laser sound effect
Add code when laser is fired:

AudioSource.Play()

It’s also possible to not drag in AudioClip to the component, but create a SerializedGield and drag in the audioClip into the Inspector. This is used when you want to play multiple AudioClips from one audio source. Example would be laser sounds, damaged sounds and explosions.
(You’ll still need to AudioSource to play the sound. )
Assign the AudioClip from the inspector to the AudioSource.Clip with the following code in Start().

_audioSource.clip = _laserAudioClip;

Then we can use the AudioSource.Play() again to play the assigned clip.

In the same manner we can add SFX to our explosions of the player and enemies.

Play SFX and destroy instantly

When we pick up a power up and we want to play a sound and destroy it instantly. This destroys the audiosource component too and no sound will be heard. There are multiple way to fix this. Our choice is using AudioSource.PlayClipAtPoint. This instantiates an empty object with an audiosource that plays the audioclip and deletes itself.

In this case we only need a reference to the AudioClip in the script. Neither do we need an audiosource component on our power ups.

Low volume or Inaudible AudioSource.PlayClipAtPoint

We need to set a position and if we use the actual powerup location it will be very quiet. This is because Unity is 3D based and the camera that picks up sound is further away. One way to fix this in 2D is to play instantiate the audio source at the position of the camera.

AudioSource.PlayClipAtPoint(_powerupSFX,Camera.main.transform.position);

--

--

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.