using System.Collections; using System.Collections.Generic; using UnityEngine; public class AudioManager : MonoBehaviour { public static AudioManager Instance { get; private set; } private AudioSource bgmSource; private List sfxSources = new List(); [Header("音量设置")] [Range(0f, 1f)] public float bgmVolume = 1f; [Range(0f, 1f)] public float sfxVolume = 1f; private void Awake() { if (Instance != null) { Destroy(gameObject); return; } Instance = this; DontDestroyOnLoad(gameObject); bgmSource = gameObject.AddComponent(); bgmSource.loop = true; } public void PlayBGM(string bgmName) { AudioClip clip = Resources.Load($"Audio/{bgmName}"); if (clip == null) { Debug.LogWarning($"未找到BGM: {bgmName}"); return; } bgmSource.clip = clip; bgmSource.volume = bgmVolume; bgmSource.Play(); } public void StopBGM() { bgmSource.Stop(); } public void PlaySFX(string sfxName) { AudioClip clip = Resources.Load($"Audio/{sfxName}"); if (clip == null) { Debug.LogWarning($"未找到音效: {sfxName}"); return; } AudioSource source = gameObject.AddComponent(); source.clip = clip; source.volume = sfxVolume; source.Play(); sfxSources.Add(source); StartCoroutine(DestroySFXWhenDone(source)); } private IEnumerator DestroySFXWhenDone(AudioSource source) { yield return new WaitForSeconds(source.clip.length); sfxSources.Remove(source); Destroy(source); } public void SetVolume(SoundType type, float volume) { if (type == SoundType.BGM) { bgmVolume = volume; bgmSource.volume = volume; } else if (type == SoundType.SFX) { sfxVolume = volume; foreach (var source in sfxSources) { source.volume = volume; } } } public void Mute(bool mute) { bgmSource.mute = mute; foreach (var source in sfxSources) { source.mute = mute; } } }