using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class AudioManager : MonoBehaviour { public static AudioManager Instance; public AudioLibraryObject audioLibrary; private void OnEnable() { if (Instance is null) { Instance = this; // TODO: manager itself should not handle this // DontDestroyOnLoad(this); } else { Destroy(this); } } private void OnDisable() { Instance = null; } public static AudioClip FindAudioClip(string nameOfClip) { return Instance.audioLibrary.Clips.First(x => x.name == nameOfClip); } public static AudioSource PlaySound(string nameOfClip, Vector3 sourcePos, bool is3D, bool loop = false, bool fadeIn = false) { if (Instance == null) { Debug.LogWarning("AudioManager has not been initialized. Please initialize it before use."); return null; } var sourceObject = new GameObject("SoundSource"); var audioSource = sourceObject.AddComponent(); audioSource.loop = loop; audioSource.clip = FindAudioClip(nameOfClip); sourceObject.transform.position = sourcePos; if (is3D) { audioSource.rolloffMode = AudioRolloffMode.Linear; audioSource.spatialBlend = 1f; } Instance.StartCoroutine(Instance.StartSound(audioSource, fadeIn)); return audioSource; } public static List AliveSources = new List(); IEnumerator StartSound(AudioSource audioSource, bool fadeIn = false) { AliveSources.Add(new SoundSource(audioSource)); if (fadeIn) { audioSource.volume = 0; StartCoroutine(StartMusicFadeIn(audioSource)); } audioSource.Play(); yield return new WaitUntil(() => !audioSource.isPlaying); Destroy(audioSource.gameObject); } public IEnumerator StartMusicFadeIn(AudioSource AS) { while (true) { if (AS.volume >= 1) { break; } AS.volume += 0.01f; yield return new WaitForSecondsRealtime(0.05f); } } } public class SoundSource { public string Id { get; set; } public AudioSource source { get; set; } public SoundSource(AudioSource originalSource) { source = originalSource; } }