/*
* author: mark joshwel
* date: 29/5/2024
* description: audio manager for handling audio in the game
*/
using System;
using UnityEngine;
///
/// singleton class for handling audio in the game
///
public class AudioManager : MonoBehaviour
{
///
/// singleton pattern: define instance field for accessing the singleton elsewhere
///
public static AudioManager Instance;
///
/// music audio source
///
[SerializeField] private AudioSource musicSource;
///
/// music source default volume
///
[SerializeField] private float musicSourceDefaultVolume = 0.6f;
///
/// sound effects (sfx) audio source
///
[SerializeField] private AudioSource sfxSource;
///
/// sound effects (sfx) source default volume
///
[SerializeField] private float sfxSourceDefaultVolume = 0.6f;
///
/// audio clip for menu button click
///
[SerializeField] public AudioClip menuButtonClick;
///
/// audio clip for menu button hover
///
[SerializeField] public AudioClip menuButtonHover;
///
/// function to set don't destroy on load and check for multiple instances
///
private void Awake()
{
// check if instance hasn't been set yet
if (Instance == null)
{
// set this instance as the singleton instance
Instance = this;
// don't destroy this instance on scene load
DontDestroyOnLoad(gameObject);
Debug.Log("AudioManager: Awake as singleton instance");
}
// check if instance is already set and it's not this instance
else if (Instance != null && Instance != this)
{
Debug.Log("AudioManager: Awake as non-singleton instance, destroying self");
// destroy the new instance if it's not the singleton instance
Destroy(gameObject);
}
}
///
/// function to set default volumes for the audio sources
///
public void Start()
{
// set the default volume for the music source
musicSource.volume = musicSourceDefaultVolume;
// set the default volume for the sfx source
sfxSource.volume = sfxSourceDefaultVolume;
}
///
/// plays the audio clip once on the music source/channel
///
/// audio clip to play
public void PlayOnMusicChannel(AudioClip clip)
{
musicSource.PlayOneShot(clip);
}
///
/// plays the audio clip once on the sound effects (sfx) source/channel
///
/// audio clip to play
public void PlayOnSFXChannel(AudioClip clip)
{
sfxSource.PlayOneShot(clip);
}
///
/// function to get the current volume of the music source/channel
///
/// volume as float from 0.0 to 1.0
public float GetMusicVolume()
{
return musicSource.volume;
}
///
/// sets the volume of the music source/channel
///
/// float (0.0-1.0) to set the channel volume to
public void SetMusicVolume(float volume)
{
musicSource.volume = Math.Min(volume, 1.0f);
}
///
/// function to get the current volume of the sound effects (sfx) source/channel
///
/// volume as float from 0.0 to 1.0
public float GetSfxVolume()
{
return sfxSource.volume;
}
///
/// sets the volume of the sound effects (sfx) source/channel
///
/// float (0.0-1.0) to set the channel volume to
public void SetSfxVolume(float volume)
{
sfxSource.volume = Math.Min(volume, 1.0f);
}
}