Journal 29 — How to Play Sound Effects in Unity
In the previous Journal, we learned about adding audio to a game to play in the background. Now we want to add sound effects for:
— when lasers are fired
— when the Player is destroyed
— when the asteroid is destroyed at the beginning level to start the spawn waves
— when an enemy is destroyed
— when a power up is collected
To add sound effects to the laser, and the Player destroyed, we add references to the Audio Source component and an audio clip in the Player C# script.
In Void Start, we add a reference to the Audio Source component, and we can assign the laser sound as the audio clip.
In the Player script, when we hit the spacebar and fire the laser, we play the audio clip.
During Playmode, you can see the results where the laser is added to the Audio Source component.
In the Player script, where the player’s lives are checked at less than 1, we add a reference to play the audio clip, and also update the destroy command to delay by two seconds, in order to play the audio clip.
In the Player game object, we add the Audio Source component and drag the audio clips to the Inspector.
For the asteroid, we can add the sound to the explosion game object for when it’s instantiated. Similar to the Player script, we add a variable for the Audio Source component and audio clip to the Explosion script. In Void Start, we add a reference to the Audio Source and play the explosion sound.
In the Explosion prefab, we add the audio clip and Audio Source component.
During testing, I found that if you rapidly fire your laser, you may hear multiple explosions on the asteroid, instead of just one. You can fix this by disabling the asteroid’s collider in its script, right after the explosion is called.
For the enemy explosions, we add similar code like the above examples to the Enemy script.
Finally, for the power up sounds, we can add the variables and reference to the Audio Source component and audio clip.
In the powerup script, we can play the audio clip when the Player touches the power up. In order for the power up audio clip to play completely, we can disable the sprite renderer and delay the destroy command briefly.
On each power up, we drag in the audio clip, and we attach the Audio Source component.
After running through all these steps, all the sounds have been successfully tested. You should confirm that all the Audio Source components are attached to game objects, and make some adjustments to their respective volume settings to your liking, because some of these clips can come off very loud.
Thank you for stopping by!