using System.Collections.Generic; using UnityEngine; public class SoundManager { AudioSource[] _audioSources = new AudioSource[(int)Define.Sound.MaxCount]; Dictionary _audioClips = new Dictionary(); public void Init() { GameObject root = GameObject.Find("@Sound"); if (root == null) root = new GameObject { name = "@Sound" }; Object.DontDestroyOnLoad(root); string[] soundNames = System.Enum.GetNames(typeof(Define.Sound)); for (int i = 0; i < soundNames.Length -1; i++) { GameObject go = new GameObject { name = soundNames[i] }; _audioSources[i] = go.AddComponent(); go.transform.parent = root.transform; } _audioSources[(int)Define.Sound.Bgm].loop = true; } // 이걸 해줘야 오디오 리소스 캐싱으로 인해서 메모리가 차는 문제를 해결할 수 있다. public void Clear() { foreach (AudioSource audioSource in _audioSources) { audioSource.clip = null; audioSource.Stop(); } _audioClips.Clear(); } public void Play(string path, Define.Sound type = Define.Sound.Effect, float pitch = 1.0f) { AudioClip audioClip = GetOrAddAudioClip(path, type); Play(audioClip, type, pitch); } public void Play(AudioClip audioClip, Define.Sound type = Define.Sound.Effect, float pitch = 1.0f) { if (audioClip == null) { Debug.LogError($"Sound not found"); return; } if (type == Define.Sound.Bgm) { AudioSource audioSource = _audioSources[(int)Define.Sound.Bgm]; if(audioSource.isPlaying) audioSource.Stop(); audioSource.pitch = pitch; audioSource.clip = audioClip; audioSource.Play(); } else { AudioSource audioSource = _audioSources[(int)Define.Sound.Effect]; audioSource.pitch = pitch; audioSource.PlayOneShot(audioClip); } } // 캐싱 기능을 위한 함수임 - 근데 위에 딕셔너리로 잡고 있어서 이게 메모리 이슈가 될 수 있으니 주의 해야함 // Clear 함수를 해줘야 하는이유임 AudioClip GetOrAddAudioClip(string path, Define.Sound type = Define.Sound.Effect) { if(path.Contains("Sounds/") == false) path = $"Sounds/{path}"; AudioClip audioClip = null; if (type == Define.Sound.Bgm) { audioClip = Managers.Resource.Load(path); } else { if (_audioClips.TryGetValue(path, out audioClip) == false) { audioClip = Managers.Resource.Load(path); _audioClips.Add(path, audioClip); } } if (audioClip == null) Debug.LogError($"AudioClip Missing! {path}"); return audioClip; } }