using System.Collections.Generic; using UnityEngine; using Game; using Music; using Player; namespace Music { /// /// This class manages the playback of sound effects in the game. /// It provides functionality to play specific sounds by name and ensures a singleton instance for global access. /// public class AudioManager : MonoBehaviour { /// /// A list of all sound effects managed by the AudioManager. /// public List soundEffects = new List(); /// /// The singleton instance of the class. /// public static AudioManager Instance; /// /// Initializes the singleton instance and loads all child AudioSources as sound effects. /// private void Awake() { // Ensure only one instance of the AudioManager exists if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); // Persist across scenes } else { Destroy(gameObject); // Destroy duplicate instances } // Load all child AudioSources into the soundEffects list foreach (Transform child in transform) { var soundEffect = new SoundEffect(child.name, child.GetComponent()); if (soundEffect != null) { soundEffects.Add(soundEffect); } } } /// /// Plays a sound effect by its name. /// /// The name of the sound effect to play. /// /// If the sound name is "Punch," it plays multiple punch-related sound effects. /// If the sound is not found, a warning is logged to the console. /// public void PlaySound(string soundName) { // Special case: Play multiple punch sound effects if (soundName == "Punch") { soundEffects.Find(x => x.name == "Punch").audioSource.Play(); soundEffects.Find(x => x.name == "Punch 2").audioSource.Play(); soundEffects.Find(x => x.name == "Punch 3").audioSource.Play(); return; } // Find and play the sound effect by name foreach (var soundEffect in soundEffects) { if (soundEffect.name == soundName) { soundEffect.audioSource.Play(); return; } } // Log a warning if the sound effect is not found Debug.LogWarning($"Sound '{soundName}' not found!"); } } /// /// Represents a sound effect, including its name and associated AudioSource. /// public class SoundEffect { /// /// The name of the sound effect. /// public string name; /// /// The AudioSource component that plays the sound effect. /// public AudioSource audioSource; /// /// Initializes a new instance of the class. /// /// The name of the sound effect. /// The AudioSource component for the sound effect. public SoundEffect(string name, AudioSource audioSource) { this.name = name; this.audioSource = audioSource; } } }