Skip to content

Instantly share code, notes, and snippets.

@david-alejandro-reyes-milian
Created July 10, 2022 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-alejandro-reyes-milian/d218a98f2867296ca752f6ef005a39a6 to your computer and use it in GitHub Desktop.
Save david-alejandro-reyes-milian/d218a98f2867296ca752f6ef005a39a6 to your computer and use it in GitHub Desktop.
Easy to use AudioManager. Creates an audio source connected to an audio output to enable easy audio mixing.
using System;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
private static AudioManager _instance;
public Sound[] sounds;
private readonly Dictionary<string, Sound> _soundDictionary = new Dictionary<string, Sound>();
private void Awake()
{
if (_instance != null) Destroy(gameObject);
else
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
foreach (var s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.loop = s.loop;
s.source.outputAudioMixerGroup = s.mixerGroup;
_soundDictionary.Add(s.source.clip.name, s);
}
}
public void Play(string soundName, bool reverse = false)
{
var source = FindSound(soundName)?.source;
if (source == null) return;
source.pitch = reverse ? -1 : 1;
source.time = reverse ? source.clip.length - 0.01f : 0f;
source.Play();
}
private Sound FindSound(string soundName)
{
try
{
return _soundDictionary[soundName];
}
catch (Exception)
{
Debug.LogError("Sound: " + soundName + " not found!");
return null;
}
}
}
using System;
using UnityEngine;
using UnityEngine.Audio;
[Serializable]
public class Sound
{
public AudioClip clip;
public bool loop;
public AudioMixerGroup mixerGroup;
[HideInInspector] public AudioSource source;
}
@david-alejandro-reyes-milian
Copy link
Author

image

@david-alejandro-reyes-milian
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment