Singleton: Audio Manager

Objective: Create a singleton audio manager to handle sound in game.

Create a empty game object naming it Audio_Manager. Create two more empty game objects as children of the Audio_Manager, naming them Voice_Over and Music. The hierarchy should appear as shown.

Audio Manager Hierarchy

Add component Audio Source to each of these children. To Music, assign Ambient_Background_Music to the AudioClip. This will play background music and allows the volume to be adjusted.

Audio source for music.

Create a C# script called AudioManager and add it to the AudioManager, shown below.

Audio Manager

The C# script is a singleton. Singletons are defined using the code below.

Audio Manager singleton script excerpt.

A singleton must be used only when there is a single instance of this object and it will not be destroyed. The private static GameManager _instance variable will be assigned to this code, but through a public static GameManager Instance variable that will be used to grant access to this script. When another script tries to get the GameManager.Instance, _instance is checked that it is not null then returned. Because _instance is private it cannot be altered, but allows access to public variables within the script. Instance is assigned on Awake as shown below.

Assigning _instance in the GameManager script.

A serialize field allows the _voiceOver audio source to be assigned in the inspector, as shown in the Audio Manager three images above.

AudioSource variable using serialize field.

A public method is used to PlayeVoiceOver method which expects an AudioClip clipToPlay input which will be assigned to the audio source _voiceOver and then played, see below.

PlayVoiceOver method in AudioManager script.

Now the VoiceOverTrigger script can use the AudioManager class to play an audio clip based on the trigger to which it is attached. The command AudioManager.Instance.PlayVoiceOver feeds the _audioClip to the AudioManager where it is played on the Voice_Over audio source.


In summary, a singleton contains a private static or class reference to the script itself, which is accessible through a public static or class variable. This script can contain public variables or methods which can now be easily accessed.

Software engineer