Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Last active January 24, 2023 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtdekker/3e81492863526c160077a16957369a94 to your computer and use it in GitHub Desktop.
Save kurtdekker/3e81492863526c160077a16957369a94 to your computer and use it in GitHub Desktop.
Ultra simple Music Manager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// @kurtdekker - example of an ultra-simple music manager.
//
// How to use:
// MusicManager.Instance.PlayMusic( Audioclip clip);
//
// Call the above with null to stop music.
//
// Do NOT drop this into a scene!! Just use it from code as above.
//
public class MusicManager : MonoBehaviour
{
static MusicManager _instance;
public static MusicManager Instance
{
get
{
if (!_instance)
{
_instance = new GameObject( "MusicManager").AddComponent<MusicManager>();
DontDestroyOnLoad(_instance);
}
return _instance;
}
}
const float crossFadeTime = 1.0f;
// stays zero when not phasing from one song to the next
float fading;
AudioSource Current;
AudioSource Previous;
public void PlayMusic( AudioClip clip)
{
if (Current)
{
if (Current.clip == clip) return;
}
if (Previous)
{
Destroy( Previous);
Previous = null;
}
Previous = Current;
Current = gameObject.AddComponent<AudioSource>();
Current.clip = clip;
Current.loop = true;
Current.volume = 0;
Current.bypassListenerEffects = true;
Current.Play();
fading = 0.001f;
}
void Update()
{
if (fading > 0)
{
float fraction = fading / crossFadeTime;
fraction = Mathf.Clamp01( fraction);
// crossfade
if (Previous)
{
float volume = 1.0f - fraction;
Previous.volume = volume;
}
if (Current)
{
float volume = fraction;
Current.volume = volume;
}
fading += Time.deltaTime;
if (fraction >= 1)
{
fading = 0.0f;
if (Previous)
{
Destroy( Previous);
Previous = null;
}
}
}
}
}
// example of how to use...
using UnityEngine;
public class TestMusicManager : MonoBehaviour
{
public AudioClip Song1;
public AudioClip Song2;
void Update ()
{
if (Input.GetKeyDown( KeyCode.Alpha1))
{
MusicManager.Instance.PlayMusic(Song1);
}
if (Input.GetKeyDown( KeyCode.Alpha2))
{
MusicManager.Instance.PlayMusic(Song2);
}
if (Input.GetKeyDown( KeyCode.Alpha3))
{
MusicManager.Instance.PlayMusic(null); // silence
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment