File size: 2,101 Bytes
6cae93f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | using UnityEngine;
namespace UnityAgent
{
/// <summary>
/// Singleton audio manager that exposes named one-shot SFX and music
/// channels. Used by other systems to play clips without having to manage
/// their own AudioSource components.
/// </summary>
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance { get; private set; }
[Header("Mixers")]
public AudioSource sfxSource;
public AudioSource musicSource;
[Range(0f, 1f)] public float masterVolume = 1f;
[Range(0f, 1f)] public float sfxVolume = 0.8f;
[Range(0f, 1f)] public float musicVolume = 0.5f;
private void Awake()
{
if (Instance != null && Instance != this) { Destroy(gameObject); return; }
Instance = this;
DontDestroyOnLoad(gameObject);
if (sfxSource == null)
{
sfxSource = gameObject.AddComponent<AudioSource>();
sfxSource.playOnAwake = false;
}
if (musicSource == null)
{
musicSource = gameObject.AddComponent<AudioSource>();
musicSource.loop = true;
musicSource.playOnAwake = false;
}
ApplyVolumes();
}
public void PlaySfx(AudioClip clip, float volumeScale = 1f)
{
if (clip != null && sfxSource != null)
sfxSource.PlayOneShot(clip, volumeScale * sfxVolume * masterVolume);
}
public void PlayMusic(AudioClip clip)
{
if (clip == null || musicSource == null) return;
musicSource.clip = clip;
musicSource.volume = musicVolume * masterVolume;
musicSource.Play();
}
public void StopMusic()
{
if (musicSource != null) musicSource.Stop();
}
public void ApplyVolumes()
{
if (musicSource != null) musicSource.volume = musicVolume * masterVolume;
AudioListener.volume = masterVolume;
}
}
}
|