How to create an Audio Manager in Unity
In this article we will create an audio manager to play our voice over tracks.
Setup for Audio Manager
Create Empty Game Object > Reset Transform > Rename to AudioManager
Create C# Script > AudioManager > Attach to AudioManager GameObject
Create Empty Game Object > Reset Transform > Rename to VO > Set as Child of AudioManager > Add Component > Audio Source
AudioManager Script
There will be only one instance of this manager class so we will make it a singleton.
We create a handle for our voice over audio source we’ve created earlier.
Make sure to turn off play on awake and loop on the audio source.
Lastly we made a public method to take in audioclips and play them. This will be called from our voice over triggers that feed the audioclips as well.
private static AudioManager _instance;
public static AudioManager Instance
{
get
{
if (_instance == null)
{
Debug.LogError("audio manager is NULL!");
}
return _instance;
}
}
public AudioSource voiceOver;
private void Awake()
{
_instance = this;
}
public void PlayVoiceOver(AudioClip voiceOverClip)
{
voiceOver.clip = voiceOverClip;
voiceOver.Play();
}
VoiceOverTrigger Script updated
The important changes are in bold. We assign the audioclip in the inspector to it.
When it gets triggered we access the audio manager and send them the audio clip to play.
public AudioClip _audioClip;
private bool _isPlayed = false;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player" && _isPlayed == false)
{
AudioManager.Instance.PlayVoiceOver(_audioClip);
_isPlayed = true;
}
}