An “Audio Manager” is a game object in your hierarchy that will control your in-game audio. It will manage audio triggers, play audio when needed, and keep everything organized and in line with “Best Practices”.
To start, you’ll want to create a new game object in your hierarchy and name it “Audio Manager”. You are welcome to name this whatever you like but I would recommend this name, as simple and straightforward naming conventions are oftentimes the better option. Other people who may eventually work on your project, or even you coming back to it after working on something else for a while will be thankful for this, trust me.
Next, you will need to create a new C# script and you will also name this “AudioManager”. This makes it easy to know which object this should be attached to. Add this new script to your “Audio Manager” game object and let’s jump into the code.
For the first bit of this script let’s add a Singleton as this will be the ONLY instance of the Audio Manager game object and it will help with referencing here shortly.
If you haven’t seen my previous article on “Using Singletons & Static Variables To Create Manager Classes In Unity” then you should go check that out… But in the meantime, here’s what the “Singleton” looks like.
For the next part, you’ll need to create another new game object and add it as a child underneath your “Audio Manager” object. You can name this whatever you want, but I’m going to call it “Audio” for this example. You will then need to add an “Audio Source” component to this object. This is what actually controls the audio and allows it to play.
Within the “Audio Source” component there are settings that you can adjust such as volume, pitch, stereo pan, etc. You can even set the audio to “Play On Awake” which means as soon as this object is loaded or even “Loop” the audio indefinitely!
For this example, we will be unchecking “Play On Awake” since our audio is only going to play once it’s triggered.
Next, create another new game object, but this time add a trigger collider to it and place it in your scene like a tripwire wherever you want your audio to be triggered.
Then create a new C# script and attach it to the new trigger object. This script will be used to specify and play your audio when the player enters the collider.
Last but not least, you’ll need to attach the reference of the audio clip that you would like to play to the “_clipToPlay” reference on the script component that is attached to your trigger object.
Well, there it is. Thanks for reading and I will see you next time!