open-world-city-unity / Assets /Scripts /AudioManager.cs
ryzerrr's picture
Upload folder using huggingface_hub
6cae93f verified
Raw
History Blame Contribute Delete
2.1 kB
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;
}
}
}