Skip to content

Instantly share code, notes, and snippets.

@twobob
Forked from YoriKv/SimpleSoundManager.cs
Created September 4, 2018 14:09
Show Gist options
  • Save twobob/a43adaf9eb2b64d6e3d41bca9805a6e2 to your computer and use it in GitHub Desktop.
Save twobob/a43adaf9eb2b64d6e3d41bca9805a6e2 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class SimpleSoundManager:MonoBehaviour {
// Audio source
private AudioSource musicSrc;
private AudioSource effectSrc;
// Instance variable
private static SimpleSoundManager instance;
// Instance
public static SimpleSoundManager I {
get {
if(instance == null && Application.isPlaying) {
// Create container gameobject
GameObject smc = new GameObject("SimpleSoundManagerContainer");
DontDestroyOnLoad(smc); // Persist
// Add sound manager as component
instance = smc.AddComponent<SimpleSoundManager>();
}
return instance;
}
}
// Volume
public float MusicVolume {
get { return musicSrc.volume; }
set { musicSrc.volume = value; }
}
public float EffectVolume {
get { return effectSrc.volume; }
set { effectSrc.volume = value; }
}
// Init audio sources
public void Awake() {
// Add audio sources
musicSrc = gameObject.AddComponent<AudioSource>();
effectSrc = gameObject.AddComponent<AudioSource>();
// Set volumes
EffectVolume = MusicVolume = 1f;
}
/*********************** EFFECTS & MUSIC ****************************/
// Single Effect
public void PlayEffectOnce(AudioClip snd) {
effectSrc.PlayOneShot(snd);
}
// Random Effect from list
public void PlayEffectOnce(AudioClip[] snds) {
if(snds.Length > 0)
PlayEffectOnce(snds[Random.Range(0, snds.Length)]);
}
// Music
public void PlayMusic(AudioClip snd, bool loop) {
musicSrc.clip = snd;
musicSrc.loop = loop;
musicSrc.Play();
}
public void StopMusic() {
musicSrc.Stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment