81 lines
1.8 KiBLFS
C#
81 lines
1.8 KiBLFS
C#
using System;
|
|
using System.Collections;
|
|
using UnityEngine;
|
|
|
|
[Serializable]
|
|
public class Music
|
|
{
|
|
public string sceneName;
|
|
public AudioClip clip;
|
|
}
|
|
|
|
|
|
public class MusicManager : MonoBehaviour
|
|
{
|
|
[SerializeField] private AudioSource audioSource;
|
|
|
|
[SerializeField] private Music[] musics;
|
|
|
|
[SerializeField] private float transitionTime = 1f;
|
|
|
|
[SerializeField] private float maxVolume = 1f;
|
|
|
|
private Music currentMusic;
|
|
|
|
private ulong RandomDelay => (ulong)UnityEngine.Random.Range(1f, 3f);
|
|
|
|
|
|
public void GoToScene(string sceneName)
|
|
{
|
|
var music = Array.Find(musics, m => m.sceneName == sceneName);
|
|
if (music == null) return;
|
|
PlayMusic(music);
|
|
}
|
|
|
|
public void PlayMusic(Music newMusic)
|
|
{
|
|
if (currentMusic == null)
|
|
{
|
|
currentMusic = newMusic;
|
|
audioSource.clip = currentMusic.clip;
|
|
audioSource.PlayDelayed(RandomDelay);
|
|
return;
|
|
}
|
|
|
|
StartCoroutine(TransitionToNewMusic(newMusic.clip));
|
|
}
|
|
private IEnumerator TransitionToNewMusic(AudioClip audioClip)
|
|
{
|
|
float timer = 0f;
|
|
|
|
while (timer < transitionTime)
|
|
{
|
|
timer += Time.deltaTime;
|
|
audioSource.volume = (1 - timer / transitionTime) * maxVolume;
|
|
yield return null;
|
|
}
|
|
|
|
audioSource.clip = audioClip;
|
|
audioSource.PlayDelayed(RandomDelay);
|
|
|
|
timer = 0f;
|
|
|
|
while (timer < transitionTime)
|
|
{
|
|
timer += Time.deltaTime;
|
|
audioSource.volume = (timer / transitionTime) * maxVolume;
|
|
yield return null;
|
|
}
|
|
}
|
|
|
|
public void PauseMusic()
|
|
{
|
|
audioSource.Pause();
|
|
}
|
|
|
|
public void ResumeMusic()
|
|
{
|
|
audioSource.UnPause();
|
|
}
|
|
}
|