82 lines
2.3 KiB
C#

using System.Collections;
using UnityEngine;
namespace Management
{
[RequireComponent(typeof(AudioSource))]
public class BGM : MonoBehaviour
{
private static BGM _instance;
private AudioSource _audioSource;
private float _originalVolume;
public void FadeIn(AudioClip clip, float t = 1f)
{
if (clip == null)
{
Debug.LogWarning("BGM: Selected clip is null");
return;
}
StopAllCoroutines();
if (t <= 0)
{
_audioSource.Stop();
_audioSource.clip = clip;
_audioSource.Play();
_audioSource.volume = _originalVolume;
}
else
{
StartCoroutine(FadeInRoutine(clip, t));
}
}
private IEnumerator FadeInRoutine(AudioClip clip, float t)
{
var timer = 0f;
var startVolume = _audioSource.volume;
var fadeInTarget = _audioSource.isPlaying ? t / 2f : t;
if (_audioSource.isPlaying)
{
while (timer < t / 2f)
{
timer += Time.deltaTime;
_audioSource.volume = Mathf.Lerp(startVolume, 0f, timer / (t / 2f));
yield return null;
}
_audioSource.volume = 0f;
timer = 0f;
}
_audioSource.Stop();
_audioSource.clip = clip;
_audioSource.Play();
while (timer < fadeInTarget)
{
timer += Time.deltaTime;
_audioSource.volume = Mathf.Lerp(0f, _originalVolume, timer / fadeInTarget);
yield return null;
}
_audioSource.volume = _originalVolume;
}
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(gameObject);
return;
}
_instance = this;
_audioSource = GetComponent<AudioSource>();
_originalVolume = _audioSource.volume;
DontDestroyOnLoad(gameObject);
}
}
}