Skip to content

Instantly share code, notes, and snippets.

@arunkarnann
Last active March 27, 2018 18:34
Show Gist options
  • Save arunkarnann/4c663865123370c6584a79d00f2c118f to your computer and use it in GitHub Desktop.
Save arunkarnann/4c663865123370c6584a79d00f2c118f to your computer and use it in GitHub Desktop.
Simple Sound Manger Thats Plays any sound and takes care of overlaps and Volume. UNITY3D , Unity3D c#
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Sound Manager Script for all types of Games :: @arunkarnan
/// </summary>
[System.Serializable]
public class SoundData
{
public SoundManager.Sounds soundEnum;
public AudioClip audioClip;
[Range(0.0f, 1.0f)]
public float volume = 1.0f;
}
public class AudioSourceData
{
public SoundManager.Sounds soundEnum;
public AudioSource source;
public AudioSourceData(SoundManager.Sounds soundEnum, AudioSource source)
{
this.soundEnum = soundEnum;
this.source = source;
}
}
public class SoundManager : MonoBehaviour
{
public static SoundManager singleton;
public static bool mute=false;
public enum Sounds
{
mainloop,
win,
lose,
button
}
public List<AudioSourceData> audioSources = new List<AudioSourceData>();
public List<SoundData> soundDataList;
public void muteSound(){
if (this.GetComponent<AudioSource> ().loop) {
this.GetComponent<AudioSource> ().Stop ();
}
}
public void Play(Sounds soundEnum, bool loop = false)
{
if (!mute) {
SoundData soundData = soundDataList.Find (x => x.soundEnum == soundEnum);
var foundSource = audioSources.Find (x => !x.source.isPlaying);
if (foundSource != null) {
foundSource.source.loop = loop;
foundSource.source.clip = soundData.audioClip;
foundSource.source.volume = soundData.volume;
foundSource.source.Play ();
} else {
audioSources.Add (new AudioSourceData (soundEnum, gameObject.AddComponent<AudioSource> ()));
audioSources [audioSources.Count - 1].source.loop = loop;
audioSources [audioSources.Count - 1].source.clip = soundData.audioClip;
audioSources [audioSources.Count - 1].source.volume = soundData.volume;
audioSources [audioSources.Count - 1].source.Play ();
}
}
}
void Update()
{
if (!mute) {
var sourcesToDelete = audioSources.FindAll (x => !x.source.isPlaying);
sourcesToDelete.ForEach (x => Destroy (x.source));
sourcesToDelete.ForEach (x => audioSources.Remove (x));
}
}
void Awake(){
if (singleton == null) {
singleton = this;
}
}
public void Stop(Sounds soundEnum)
{
audioSources
.FindAll(x => x.soundEnum == soundEnum)
.ForEach(x => x.source.Stop());
}
public void PlaySwipeSound(){
//Play (SoundManager.Sounds.button, false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment