Hello, I hope everyone is doing well. As a recap, over the last three months, I have learned how to set up a mock level or game scene for a 3D platformer by creating: player and character movement, player health system (including death and respawn), checkpoints, health object pickup, and collectible items. Today, I will set up and add background music to the game along with sound effects (sfx) for some of the objects.
As a preface, setting up the music and sfx system in Unity is actually a tad more complicated than I expected. If there is more than one music track and sound effect in the game (which is often the case), a script will actually need to be used. Thus, to begin with, the ‘AudioManager‘ script is created:
Once the ‘AudioManager’ script is created, it is attached to the “Systems Manager” in Unity. Fortunately, the rest of the work is fairly intuitive. Next, the music and sfx files are dragged into or assigned to their respective arrays:
Each ‘Music Source’ or ‘SFX Source’ added to the scene has its own Audio Source component. Here, various parameters (such as volume and pitch) can be adjusted for each individual music track or sound effect:
However, there is often an additional need to control the overall volume or audio output for all music and sfx in the game as well (rather than just individual tracks and sfx). This can be done by adding an AudioMixer in Unity:
Finally, to assign a sound effect to an object, the ‘PlaySFX()’ function in the AudioManager is called wherever appropriate (from other scripts). For example, in the ‘CoinPickup’ script:
The appropriate sfx array element is then assigned to the game object/prefab:
At long last, we now have something aesthetically pleasing to the ears as well! It really makes you think how much more enjoyable having music and sound effects are in a game, doesn’t it?
And with that, it looks like the next topic in the course is to add a pause menu to the game with perhaps the ability to control some of the game settings. Thanks for reading today’s blog post and do stay tuned for next week’s!