using UnityEngine; using UnityEngine.UI; namespace Crosstales.UI.Audio { /// Controller for AudioSources. public class AudioSourceController : MonoBehaviour { #region Variables /// Searches for all AudioSource in the whole scene (default: true). [Header("Audio Sources")] [Tooltip("Searches for all AudioSource in the whole scene (default: true).")] public bool FindAllAudioSourcesOnStart = true; /// Active controlled AudioSources. [Tooltip("Active controlled AudioSources.")] public AudioSource[] AudioSources; /// Resets all active AudioSources (default: true). [Header("Settings")] [Tooltip("Resets all active AudioSources (default: true).")] public bool ResetAudioSourcesOnStart = true; /// Mute on/off (default: false). [Tooltip("Mute on/off (default: false).")] public bool Mute; /// Loop on/off (default: false). [Tooltip("Loop on/off (default: false).")] public bool Loop; /// Volume of the audio (default: 1) [Tooltip("Volume of the audio (default: 1)")] public float Volume = 1f; /// Pitch of the audio (default: 1). [Tooltip("Pitch of the audio (default: 1).")] public float Pitch = 1f; /// Stereo pan of the audio (default: 0). [Tooltip("Stereo pan of the audio (default: 0).")] public float StereoPan; [Header("UI Objects")] public Text VolumeText; public Text PitchText; public Text StereoPanText; private bool initialized; #endregion #region MonoBehaviour methods private void Update() { if (!initialized && Time.frameCount % 30 == 0) { initialized = true; if (FindAllAudioSourcesOnStart) FindAllAudioSources(); if (ResetAudioSourcesOnStart) ResetAllAudioSources(); } } #endregion #region Public methods /// Finds all audio sources in the scene. public void FindAllAudioSources() { AudioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[]; } /// Resets all audio sources. public void ResetAllAudioSources() { MuteEnabled(Mute); LoopEnabled(Loop); VolumeChanged(Volume); PitchChanged(Pitch); StereoPanChanged(StereoPan); } public void MuteEnabled(bool isEnabled) { foreach (AudioSource source in AudioSources) { source.mute = isEnabled; } } public void LoopEnabled(bool isEnabled) { foreach (AudioSource source in AudioSources) { source.mute = isEnabled; } } public void VolumeChanged(float value) { foreach (AudioSource source in AudioSources) { source.volume = value; } if (VolumeText != null) VolumeText.text = value.ToString(Crosstales.Common.Util.BaseConstants.FORMAT_TWO_DECIMAL_PLACES); } public void PitchChanged(float value) { foreach (AudioSource source in AudioSources) { source.pitch = value; } if (PitchText != null) PitchText.text = value.ToString(Crosstales.Common.Util.BaseConstants.FORMAT_TWO_DECIMAL_PLACES); } public void StereoPanChanged(float value) { foreach (AudioSource source in AudioSources) { source.panStereo = value; } if (StereoPanText != null) StereoPanText.text = value.ToString(Crosstales.Common.Util.BaseConstants.FORMAT_TWO_DECIMAL_PLACES); } #endregion } } // © 2016-2023 crosstales LLC (https://www.crosstales.com)