Files
Scampz/Assets/Scripts/Audio/BGMManager.cs
2022-08-16 09:27:55 -07:00

72 lines
1.6 KiB
C#

using Scampz.GameJam.Assets.Scripts.Audio;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Scampz.GameJam.Assets.Scripts
{
public class BGMManager : MonoBehaviour
{
[SerializeField]
private BGM _backgroundMusic;
private static AudioSource _audioSource;
private void Awake()
{
if (_audioSource == null)
{
_audioSource = new GameObject().AddComponent<AudioSource>();
_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();
}
}
}