Create Immersion with Sounds in Unity
A good way to approach sounds in Unity is by creating an audio manager.
Creating a background sound
Our first objective is to add a background sound. Let’s create an empty object and call it audio manager. Then add another empty object to it called “Background Sound”. We can now add a component called Audio Source. With drag and drop we add a music clip from our assets to the AudioClip field. For the background music we want the music to play immediately, thus select “play on awake” and we want it to loop.
When we start the game, we will now have a background sound.
Giving our laser a sound using the player script
Another approach is used when we want to give a specific action a sound. Our laser for example, can have a nice sound.
We first add an Audio Source component to the player. Then we can add two variables to the player script.
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:
_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
Adding sound to the powerups
Our next objective: When the player collects one of the powerups: the shield, the triple shot or the speed bonus, we want to play a bonus sound.
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:
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: