using Scampz.GameJam.Assets.Scripts.Audio; using UnityEngine; using UnityEngine.SceneManagement; namespace Scampz.GameJam.Assets.Scripts { [RequireComponent(typeof(AudioSource))] public class BGMManager : MonoBehaviour { [SerializeField] private BGM _backgroundMusic; private static AudioSource _audioSource; private void Awake() { if (_audioSource == null) { _audioSource = new GameObject().AddComponent(); _audioSource.loop = true; DontDestroyOnLoad(_audioSource.gameObject); } if (_backgroundMusic == null) { Instantiate(_backgroundMusic); DontDestroyOnLoad(_backgroundMusic.gameObject); } } private void OnEnable() { SceneManager.activeSceneChanged += PlayNextSongIfAreaChange; } private void OnDisable() { SceneManager.activeSceneChanged -= PlayNextSongIfAreaChange; } private void PlayNextSongIfAreaChange(Scene oldScene, Scene newScene) { if (_audioSource.clip == null) { var newMusic = _backgroundMusic.GetClipFromSceneType(newScene); PlayBGM(newMusic); return; } Debug.Log($"Changed scenes to " + newScene.name); var newAudioClip = _backgroundMusic.GetClipFromSceneType(newScene); if (_audioSource.clip.name != newAudioClip.name) { PlayBGM(newAudioClip); } Debug.Log($"Playing BGM: " + _backgroundMusic.name); } public void PlayBGM(AudioClip audioClip) { if (_audioSource == null && _audioSource.clip == audioClip) return; _audioSource.Stop(); _audioSource.clip = audioClip; _audioSource.Play(); } } }