Creating an Audio Manager
Centralizing the voice over clips
As we have mentioned in the previous article about Singleton patterns being used by higher tier management scripts, we are going to assign the Audio Manager to an singleton pattern as well.
Creating the Audio Manager Singleton:
Just like how we set up the Game Manager, we need a “private static (static variables means that this class is now saved within memory and can be referenced anywhere at anytime) handle” for the instance. It is set to private because we don’t want to have anything or anyone to tamper with the settings of this manager class.
Then we need a public property which gives access to the singleton pattern. This should house the “get” setting which allows access to the singleton data or function.
Finally we finish off the singleton pattern with an Awake method to call this class before anything else has been activated. We make sure that the instance shall only be this class, and this class only.
Adding the Audio Clips:
Now that the singleton pattern is completed, it is time to add functionality to this class. Back in Unity, we first need to create an empty child object within the Audio Manager. This child object will house an modular Audio Source component which we can feed in different audio clip through different triggers.
In the script, we need to create a public handle for the new audio source component. Then we need to have a public method which can be access by the the voice over trigger script, to play the audio clip.
The property “AudioClip clipToPlay” at the method is added to reference the audio clip data that belongs to trigger we have collided with. Then we assign the empty audio source component to the collided audio clip so we can play it.
In the Voice Over Trigger script, instead of playing audio on point, we are now going to access our Audio Manager to pass in the audio clip data. The trigger script is not going to play the audio anymore since the Audio Manager is now responsible for that.