Create Immersion with Sounds in Unity

A good way to approach sounds in Unity is by creating an audio manager.

Creating a background sound

When we start the game, we will now have a background sound.

Giving our laser a sound using the player script

We first add an Audio Source component to the player. Then we can add two variables to the player script.

[SerializeField]
private AudioClip _laserSoundClip;
private AudioSource _audioSource;

The first variable allows us to assign the sound clip in the unity editor. We use the second variable to get the component of Audio Source in our script by adding to our Start ()

_audioSource = GetComponent<AudioSource>();if(_audioSource == null)
{
Debug.LogError("AudioSource on player is NULL");
}

As always it is good practice to check if the Audio Source component is there and create an error entry if it is not.

We can continue with else to assign the sound clip:

else
{
_audioSource.clip = _laserSoundClip;
}

All that remains now is to tell the game to play the sound when we shoot the laser. As there is a void FireLaser() method, this is where we add

_audioSource.Play();

Adding sound to the powerups

We need yet another approach. As the powerups get destroyed upon collision, we can’t just attach an audio source to them. So how do we solve this.

Unity has a method PlayClipAtPoint. The Scripting API documentation tells us:

Plays an AudioClip at a given position in world space.

This function creates an audio source but automatically disposes of it once the clip has finished playing.

To use it we first create handle for our audio clip in our powerup script:

[SerializeField]
private AudioClip _clip;

Making it a SerializeField allows us to assign the sound file to the variable on the powerup script in Unity.

All we need now is to access the audiosource component and call the method PlayClipAtPoint. Here is what it looks like in the script:

Passionate Game Developer and Learning Expert. I love to create games and interactive experiences using Unity, Articulate, C#, JavaScript, PHP, HTML, CSS.