12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.UI;
- using UnityEngine.Audio;
- using Sirenix.OdinInspector;
- using KairoEngine.Core;
- namespace KairoEngine.UI
- {
- public class SoundConfigurationsUI : MonoBehaviour
- {
- public AudioMixerGroup masterMixer;
- public Slider masterVolumeSlider;
- public string masterVolumeName = "masterVolume";
- public Slider musicVolumeSlider;
- public string musicVolumeName = "musicVolume";
- public Slider sfxVolumeSlider;
- public string sfxVolumeName = "sfxVolume";
- float masterVolume = 1;
- float musicVolume = 1;
- float sfxVolume = 1;
- Coroutine delayedSave;
-
- public void OnEnable()
- {
- masterVolumeSlider.onValueChanged.AddListener(delegate {UpdateMasterVolume(); });
- musicVolumeSlider.onValueChanged.AddListener(delegate {UpdateMusicVolume(); });
- sfxVolumeSlider.onValueChanged.AddListener(delegate {UpdateSfxVolume(); });
- }
- void OnDisable()
- {
- masterVolumeSlider.onValueChanged.RemoveListener(delegate {UpdateMasterVolume(); });
- musicVolumeSlider.onValueChanged.RemoveListener(delegate {UpdateMusicVolume(); });
- sfxVolumeSlider.onValueChanged.RemoveListener(delegate {UpdateSfxVolume(); });
- }
- private void UpdateMasterVolume() => UpdateVolume(masterVolumeName, masterVolumeSlider, ref masterVolume);
- private void UpdateMusicVolume() => UpdateVolume(musicVolumeName, musicVolumeSlider, ref musicVolume);
- private void UpdateSfxVolume() => UpdateVolume(sfxVolumeName, sfxVolumeSlider, ref sfxVolume);
- void Start() => LoadConfig();
- void UpdateVolume(string volumeName, Slider slider, ref float volume)
- {
- masterMixer.audioMixer.SetFloat(volumeName, Mathf.Log10(slider.value) * 20);
- volume = slider.value;
- if(delayedSave != null) StopCoroutine(delayedSave);
- delayedSave = StartCoroutine(Timer.StartRealtime(2f, SaveConfig));
- }
- void LoadConfig()
- {
- masterVolume = PlayerPrefs.GetFloat("MasterVolume", masterVolume);
- musicVolume = PlayerPrefs.GetFloat("MusicVolume", musicVolume);
- sfxVolume = PlayerPrefs.GetFloat("SFXVolume", sfxVolume);
- masterVolumeSlider.value = masterVolume;
- musicVolumeSlider.value = musicVolume;
- sfxVolumeSlider.value = sfxVolume;
- masterMixer.audioMixer.SetFloat(masterVolumeName, Mathf.Log10(masterVolume) * 20);
- masterMixer.audioMixer.SetFloat(musicVolumeName, Mathf.Log10(musicVolume) * 20);
- masterMixer.audioMixer.SetFloat(sfxVolumeName, Mathf.Log10(sfxVolume) * 20);
- }
- void SaveConfig()
- {
- PlayerPrefs.SetFloat("MasterVolume", masterVolume);
- PlayerPrefs.SetFloat("MusicVolume", musicVolume);
- PlayerPrefs.SetFloat("SFXVolume", sfxVolume);
- Debug.Log($"Master: {masterVolume} | Music: {musicVolume} | SFX: {sfxVolume}");
- }
- }
- }
|