Created
July 10, 2022 17:46
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
using UnityEngine.Audio; | |
[Serializable] | |
public class Sound | |
{ | |
public AudioClip clip; | |
public bool loop; | |
public AudioMixerGroup mixerGroup; | |
[HideInInspector] public AudioSource source; | |
} |
Author
david-alejandro-reyes-milian
commented
Jul 10, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment