“Funslingers” Devblog #22 | How to Play Sound Effects in Unity
Adding Music and SFX to our game will be more or less the same process for what we did for our Main Menu just on a much bigger scale!
To start with, we can add in our simple background music with the Audio Manger we created for our Main Menu.
Now on to add some SFX to our game, let’s do all of our UI elements first!
For our Money Counter, I want to add a Kaching! Sound effect each time the player get’s points.
I added an AudioSource component to our Money Counter Text and got reference to it in it’s script to pitch shift and play it each time the player scores points!
We can apply this same method to all of the components we want to add sound effects to in our game! However, once the player dies, I want to change the background music to a more somber theme, so we’ll need to do things slightly different. We’ll need a way to stop the background music, and play something else in it’s place.
Since the GameOver Canvas is controlled in the Player Script, let’s have our Audio Manager controlled by the Player as well.
First, I created another audiosource that will hold our GameOver Theme audioclip.
Next, I got reference to both of our Music audiosources so I can control them in the Player script.
And from here I can simply Stop() my Background Music and Play() my GameOver Music!
Our next challenge will be a walking sound effect, that is gonna require a way to play and stop an audiosource as the player starts and stops walking back and forth!
I started by giving the player their own Audio Manager to hold the walking SFX for the Player Script to access. Then inside the Movement() method, I added an if statement that would activate the walking SFX if the player’s _direction is greater than or lower than 0, and then else it would stop the walking SFX.
You’ll see that instead of putting _walkSFX.Play(), Icreated it’s own method. I did this to avoid the walking SFX audioclip being played every frame while the player is walking. So I made a simple method, that will activate the walking SFX once, as the if statement bool parameter will return false after the first call.
Then, once the player has stopped walking, _isWalking will equal false again through our else statement!
Utilizing all these methods and more, I will be able to add sound effects to any and every element in my game!
Once we have our SFX and Music all added in and sounding great, our game will be at a great point in development where we can consider it a completed playable experience! Next devblog we are gonna make the first playable build of our game!