123 lines
2.9 KiB
C#
123 lines
2.9 KiB
C#
using UnityEngine;
|
|
using UnityEngine.SceneManagement;
|
|
using System.Collections;
|
|
|
|
public class BGMManager : MonoBehaviour
|
|
{
|
|
public static BGMManager instance;
|
|
|
|
public AudioSource audioSource;
|
|
|
|
[Header("BGM Clips")]
|
|
public AudioClip menuBGM;
|
|
public AudioClip bab1BGM;
|
|
public AudioClip bab2BGM;
|
|
public AudioClip bab3BGM;
|
|
public AudioClip bab4BGM;
|
|
public AudioClip bab5BGM;
|
|
|
|
[Header("Fade Settings")]
|
|
public float fadeDuration = 1.0f;
|
|
|
|
private float musicVolume = 0.4f; // dari slider
|
|
Coroutine fadeCoroutine;
|
|
|
|
void Awake()
|
|
{
|
|
if (instance != null && instance != this)
|
|
{
|
|
Destroy(gameObject);
|
|
return;
|
|
}
|
|
|
|
instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
|
|
if (audioSource == null)
|
|
audioSource = GetComponent<AudioSource>();
|
|
|
|
audioSource.loop = true;
|
|
|
|
LoadVolume();
|
|
|
|
SceneManager.sceneLoaded += OnSceneLoaded;
|
|
}
|
|
|
|
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
|
|
{
|
|
switch (scene.name)
|
|
{
|
|
case "MainMenu":
|
|
case "StorySelect":
|
|
ChangeMusic(menuBGM);
|
|
break;
|
|
case "Bab_1":
|
|
ChangeMusic(bab1BGM);
|
|
break;
|
|
case "Bab_2":
|
|
ChangeMusic(bab2BGM);
|
|
break;
|
|
case "Bab_3":
|
|
ChangeMusic(bab3BGM);
|
|
break;
|
|
case "Bab_4":
|
|
ChangeMusic(bab4BGM);
|
|
break;
|
|
case "Bab_5":
|
|
ChangeMusic(bab5BGM);
|
|
break;
|
|
}
|
|
}
|
|
|
|
public void SetMusicVolume(float value)
|
|
{
|
|
musicVolume = value;
|
|
audioSource.volume = value;
|
|
PlayerPrefs.SetFloat("MUSIC_VOLUME", value);
|
|
}
|
|
|
|
void LoadVolume()
|
|
{
|
|
musicVolume = PlayerPrefs.GetFloat("MUSIC_VOLUME", 0.4f);
|
|
audioSource.volume = musicVolume;
|
|
}
|
|
|
|
public void ChangeMusic(AudioClip newClip)
|
|
{
|
|
if (newClip == null || audioSource == null) return;
|
|
if (audioSource.clip == newClip) return;
|
|
|
|
if (fadeCoroutine != null)
|
|
StopCoroutine(fadeCoroutine);
|
|
|
|
fadeCoroutine = StartCoroutine(FadeChange(newClip));
|
|
}
|
|
|
|
IEnumerator FadeChange(AudioClip newClip)
|
|
{
|
|
float startVolume = audioSource.volume;
|
|
|
|
float t = 0f;
|
|
while (t < fadeDuration)
|
|
{
|
|
t += Time.unscaledDeltaTime;
|
|
audioSource.volume = Mathf.Lerp(startVolume, 0f, t / fadeDuration);
|
|
yield return null;
|
|
}
|
|
|
|
audioSource.volume = 0f;
|
|
|
|
audioSource.clip = newClip;
|
|
audioSource.Play();
|
|
|
|
t = 0f;
|
|
while (t < fadeDuration)
|
|
{
|
|
t += Time.unscaledDeltaTime;
|
|
audioSource.volume = Mathf.Lerp(0f, musicVolume, t / fadeDuration);
|
|
yield return null;
|
|
}
|
|
|
|
audioSource.volume = musicVolume;
|
|
}
|
|
} |