Galaxy Shooter 2D — Sounds #15
Adding sounds to the game!
If it sounds good, whatever it looks like, it will make it look better. It will feel better. - James Slavin (DICE)
It’s time for me to add sound effects and music in my game. Before I start writing code to play sounds, it would be ideal to make a list with every action that needs sounds.
Planning everything before hand
There are three basic sounds that need to be added:
- An explosion sound effect for the player / enemy death animation.
- A powerup sound when the player picks one up.
- A laser sound effect when the player / enemy shoots.
And, in addition to that, I will add a background track.
As all projects, there should be an AudioManager to handle the music or quick 2D sound effects. But, it’s something that I have planned for another day.
Creating an empty GameObject, adding an AudioSource component to it and setting it to Play on Awake with the looping music clip will suffice for now.
For both of my Player and Enemy prefabs, I add again an AudioSource. This time, I leave it as is except for the “Play On Awake” bool, which I unticked it.
In code, I declare two variables: an AudioSource to control it through code, and an AudioClip which I will pass to the AudioSource to play it.
Instead of using the .Play() method, I use PlayOneShot(), which is a faster call, better optimized, and can play multiple sounds.
There’s a slight problem with the powerups: as soon as the player touches one, it will automatically get destroyed. This leaves no room for the AudioSource to play any clip. In that case, I’ve written the following code to play the Pickup sound.
In their respective Shoot() methods, I just have to add the same line of code and, with that, the game has now sounds and music!