Skip to content

Instantly share code, notes, and snippets.

@Ratstail91
Created August 22, 2020 03:04
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 Ratstail91/b991b3baf0f866b402893812757e1c19 to your computer and use it in GitHub Desktop.
Save Ratstail91/b991b3baf0f866b402893812757e1c19 to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour {
//singleton
static AudioManager instance = null;
//internals
AudioSource[] audioSources;
Dictionary<String, AudioClip> audioDictionary; //TODO: clear the cache on scene load?
GameObject playerObject;
//BUGFIX: don't stack sounds on the same frame
List<AudioClip> playedClips = new List<AudioClip> ();
//volume control
float loopVolume = 1;
float oneshotVolume = 1;
void Awake() {
//singleton
if (instance == null) {
instance = this;
DontDestroyOnLoad (gameObject);
} else {
Destroy (this);
return;
}
//components
audioSources = GetComponents<AudioSource> ();
audioSources[0].loop = true;
//cache loaded sounds
audioDictionary = new Dictionary<String, AudioClip> ();
}
void Update() {
playedClips.Clear ();
}
//the method called
public static void Play(String filename, Vector3 objPosition, float volume = 1.0f, bool loop = false) {
instance.PlaySound (filename, objPosition, volume, loop);
}
public static void Play(String filename, float volume = 1.0f, bool loop = false) {
instance.PlaySound (filename, volume, loop);
}
void PlaySound(String filename, Vector3 objPosition, float volume, bool loop) {
//maximum distance
if (Vector3.Distance (playerObject.transform.position, objPosition) > 1) {
return;
}
PlaySound (filename, volume, loop);
}
void PlaySound(String filename, float volume, bool loop) {
if (!audioDictionary.ContainsKey(filename)) {
LoadAsset (filename);
}
//BUGFIX
if (playedClips.Contains(audioDictionary[filename])) {
return;
}
if (loop) {
audioSources[0].clip = audioDictionary [filename];
audioSources[0].volume = volume * loopVolume;
audioSources[0].Play ();
} else {
audioSources[1].PlayOneShot (audioDictionary [filename], volume * oneshotVolume);
}
//BUGFIX
playedClips.Add (audioDictionary [filename]);
}
void LoadAsset(String filename) {
audioDictionary [filename] = Resources.Load<AudioClip> (filename);
}
public static void RegisterPlayerObject(GameObject go) {
instance.playerObject = go;
}
//volume control
public float GetLoopVolume() {
return loopVolume;
}
public void SetLoopVolume(float v) {
loopVolume = Mathf.Clamp(v, 0f, 1f);
audioSources[0].volume = loopVolume;
}
public float GetOneshotVolume() {
return oneshotVolume;
}
public void SetOneshotVolume(float v) {
oneshotVolume = Mathf.Clamp(v, 0f, 1f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment