VolumeConfigOption.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. using UnityEngine.Audio;
  6. namespace KairoEngine.Core.ConfigOptions
  7. {
  8. [CreateAssetMenu(fileName = "VolumeConfigOption", menuName = "KairoEngine/ConfigOptions/Volume", order = 1), HideMonoScript]
  9. public class VolumeConfigOption : ConfigOptionBase
  10. {
  11. [PropertyOrder(4)] public AudioMixerGroup audioMixerChannel;
  12. [PropertyOrder(4)] public AudioMixer masterMixer;
  13. [PropertyOrder(5), Range(0.0001f, 1f)] public float defaultVolume;
  14. [PropertyOrder(6), TextArea(), HideLabel, PropertySpace(4,0)] public string description;
  15. private float currentVolume = 0;
  16. public override ConfigOptionUiData GetUiData()
  17. {
  18. Debug.Log($"Current {title} is {currentVolume}");
  19. var sliderData = new ConfigOptionUiData.SliderData(0.0001f, 1f, currentVolume);
  20. return new ConfigOptionUiData(title, description, sliderData);
  21. }
  22. public override void LoadValue(bool debug)
  23. {
  24. currentVolume = PlayerPrefs.GetFloat(id, defaultVolume);
  25. masterMixer.GetFloat(id, out float oldVolume);
  26. ApplyConfig();
  27. masterMixer.GetFloat(id, out float newVolume);
  28. if(debug) Debug.Log($"{title} changed from {Mathf.Pow(10, oldVolume/20).ToString("F2")} to {Mathf.Pow(10, newVolume/20).ToString("F2")}");
  29. }
  30. public override void SetDefaultValue()
  31. {
  32. currentVolume = defaultVolume;
  33. PlayerPrefs.SetFloat(id, defaultVolume);
  34. ApplyConfig();
  35. }
  36. public override void SetValue(ConfigOptionData data, bool save = false)
  37. {
  38. PlayerPrefs.SetFloat(id, data.floatValue);
  39. currentVolume = data.floatValue;
  40. ApplyConfig();
  41. if(save) PlayerPrefs.SetFloat(id, currentVolume);
  42. }
  43. private void ApplyConfig()
  44. {
  45. var value = Mathf.Log10(currentVolume) * 20f;
  46. bool worked = masterMixer.SetFloat(id, value);
  47. if(worked == false) Debug.LogError($"Error setting volume for {title}");
  48. }
  49. [Button("Apply Default"), PropertyOrder(100), PropertySpace(4,4)]
  50. private void ApplyDefaultConfig()
  51. {
  52. currentVolume = defaultVolume;
  53. ApplyConfig();
  54. }
  55. }
  56. }