maxhacker11

MusicManager.cs

Jan 16th, 2024
1,278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | Source Code | 0 0
  1. using System.Collections;
  2. using UnityEngine;
  3.  
  4. public class MusicManager : MonoBehaviour
  5. {
  6.     public static MusicManager Instance;
  7.  
  8.     [SerializeField]
  9.     private MusicLibrary musicLibrary;
  10.     [SerializeField]
  11.     private AudioSource musicSource;
  12.  
  13.     private void Awake()
  14.     {
  15.         if (Instance != null)
  16.         {
  17.             Destroy(gameObject);
  18.         }
  19.         else
  20.         {
  21.             Instance = this;
  22.             DontDestroyOnLoad(gameObject);
  23.         }
  24.     }
  25.  
  26.     public void PlayMusic(string trackName, float fadeDuration = 0.5f)
  27.     {
  28.         StartCoroutine(AnimateMusicCrossfade(musicLibrary.GetClipFromName(trackName), fadeDuration));
  29.     }
  30.  
  31.     IEnumerator AnimateMusicCrossfade(AudioClip nextTrack, float fadeDuration = 0.5f)
  32.     {
  33.         float percent = 0;
  34.         while (percent < 1)
  35.         {
  36.             percent += Time.deltaTime * 1 / fadeDuration;
  37.             musicSource.volume = Mathf.Lerp(1f, 0, percent);
  38.             yield return null;
  39.         }
  40.  
  41.         musicSource.clip = nextTrack;
  42.         musicSource.Play();
  43.  
  44.         percent = 0;
  45.         while (percent < 1)
  46.         {
  47.             percent += Time.deltaTime * 1 / fadeDuration;
  48.             musicSource.volume = Mathf.Lerp(0, 1f, percent);
  49.             yield return null;
  50.         }
  51.     }
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment