using UnityEngine; using System.Collections.Generic; public class SoundsManager : MonoBehaviour { private static SoundsManager m_instance = null; List m_audioSourses = new List(); bool m_inited = false; Dictionary m_loadedAudioClips = new Dictionary(); //------------------------------------------------------------------ public static SoundsManager Instance { get { return m_instance; } } //------------------------------------------------------------------ void Init () { m_instance = this; AudioSource[] allAudioSources = GetComponents(); for (int i = 0; i < allAudioSources.Length; ++i) m_audioSourses.Add(allAudioSources[i]); SetVolume(1f); m_inited = true; DontDestroyOnLoad(this); } //------------------------------------------------------------------ public void SetVolume( float volumeValue ) { for ( int i = 0; i < m_audioSourses.Count; ++i ) m_audioSourses[i].volume = volumeValue; } //------------------------------------------------------------------ public AudioSource PlaySound( string soundName, float delay = 0f, bool needLoop = false, float volume = 0.6f ) { if (!GlobalsVar.gNeedPlaySounds) return null; int count = GetPlayedSoundCount(soundName); if (count > 1) return null; string filePath = "Sounds/" + soundName; AudioClip clip = null; if (m_loadedAudioClips.ContainsKey(soundName)) clip = m_loadedAudioClips[soundName]; if (!clip) { clip = Resources.Load(filePath); m_loadedAudioClips[soundName] = clip; } if (clip) { AudioSource audioSource = GetFreeAudioSource(); if (audioSource) { audioSource.volume = volume; audioSource.clip = clip; audioSource.loop = needLoop; if (delay > 0f) audioSource.PlayDelayed(delay); else audioSource.Play(); return audioSource; } else { CommonFunctions.myassert(false); return null; } } else CommonFunctions.myassert(false, soundName + "sound not found"); return null; } //------------------------------------------------------------------ int GetPlayedSoundCount(string name) { int soundCount = 0; foreach (AudioSource audioSource in m_audioSourses) { if (audioSource.isPlaying && audioSource.clip.name == name) soundCount++; } return soundCount; } //------------------------------------------------------------------ AudioSource GetFreeAudioSource() { foreach ( AudioSource audioSource in m_audioSourses ) { if (audioSource.isPlaying) continue; return audioSource; } CommonFunctions.myassert(false, ""); return null; } //------------------------------------------------------------------ public void StopAllSounds() { foreach (AudioSource audioSource in m_audioSourses) { if (audioSource.isPlaying) audioSource.Stop(); } } //------------------------------------------------------------------ public void Update () { if (!m_inited) Init(); } }