using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class AudioManager : MonoBehaviour { // instance to allow access to AudioManager public static AudioManager Instance; // Arrays to hold music and sound effects public Sound[] musicSounds, sfxSounds; // Audio sources for playing music and sound effects public AudioSource musicSource, sfxSource; private void Awake() { // Check if there is already an instance of AudioManager if (Instance == null) { // If not, set this instance and mark it to not be destroyed on scene load Instance = this; DontDestroyOnLoad(gameObject); } else { // If an instance already exists, destroy this one to enforce the singleton pattern Destroy(gameObject); } } private void Start() { //plays game theme PlayMusic("GameTheme"); } // Method to play music by name public void PlayMusic(string name) { // Find the sound object in the musicSounds array with the matching name Sound s = Array.Find(musicSounds, x => x.name == name); if (s == null) { // log an error if sound cant be found Debug.Log("Sound not Found"); } else { // If the sound is found, set it to the music source and play it musicSource.clip = s.clip; musicSource.Play(); } } // Method to play sound effects by name public void PlaySFX(string name) { // Find the sound object in the sfxSounds array with the matching name Sound s = Array.Find(sfxSounds, x => x.name == name); if (s == null) { // If the sound is not found, log an error Debug.Log("Sound not Found"); } else { // If the sound is found, play it once using PlayOneShot sfxSource.PlayOneShot(s.clip); } } }