58 lines
1.3 KiB
C#
58 lines
1.3 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
|
|
public class AudioManager : MonoBehaviour
|
|
{
|
|
public static AudioManager Instance;
|
|
public AudioSource bgmSource;
|
|
|
|
void Awake()
|
|
{
|
|
if (Instance == null)
|
|
{
|
|
Instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
}
|
|
else Destroy(gameObject);
|
|
}
|
|
|
|
public void PlayBGM(AudioClip clip, float fadeTime = 1f)
|
|
{
|
|
StartCoroutine(FadeInBGM(clip, fadeTime));
|
|
}
|
|
public void StopBGM(float fadeTime = 1f)
|
|
{
|
|
StartCoroutine(FadeOut(fadeTime));
|
|
}
|
|
|
|
|
|
IEnumerator FadeInBGM(AudioClip clip, float fadeTime)
|
|
{
|
|
if (bgmSource.isPlaying)
|
|
yield return StartCoroutine(FadeOut(fadeTime));
|
|
|
|
bgmSource.clip = clip;
|
|
bgmSource.Play();
|
|
|
|
float t = 0f;
|
|
while (t < fadeTime)
|
|
{
|
|
t += Time.deltaTime;
|
|
bgmSource.volume = Mathf.Lerp(0, 1, t / fadeTime);
|
|
yield return null;
|
|
}
|
|
}
|
|
|
|
IEnumerator FadeOut(float fadeTime)
|
|
{
|
|
float startVol = bgmSource.volume;
|
|
float t = 0f;
|
|
while (t < fadeTime)
|
|
{
|
|
t += Time.deltaTime;
|
|
bgmSource.volume = Mathf.Lerp(startVol, 0, t / fadeTime);
|
|
yield return null;
|
|
}
|
|
bgmSource.Stop();
|
|
}
|
|
} |