SliderText.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using TMPro;
  6. using Sirenix.OdinInspector;
  7. using KairoEngine.Core;
  8. namespace KairoEngine.UI
  9. {
  10. public class SliderText : MonoBehaviour
  11. {
  12. public enum TextType
  13. {
  14. Percentage,
  15. CurrentMax
  16. }
  17. public TextType textType = TextType.Percentage;
  18. public TextMeshProUGUI text;
  19. [ShowIf("@textType == TextType.Percentage")] public string suffix = "%";
  20. [ShowIf("@textType == TextType.Percentage")] public float multiplier = 100;
  21. [ShowIf("@textType == TextType.CurrentMax")] public string separator = "/";
  22. public bool hideEmptyFill = false;
  23. public Slider slider;
  24. public void OnEnable()
  25. {
  26. slider.onValueChanged.AddListener(delegate {UpdateText(); });
  27. }
  28. void OnDisable()
  29. {
  30. slider.onValueChanged.RemoveListener(delegate {UpdateText(); });
  31. }
  32. void Start()
  33. {
  34. UpdateText();
  35. }
  36. [OnInspectorInit]
  37. public void UpdateText()
  38. {
  39. if(textType == TextType.Percentage)
  40. {
  41. float value = slider.value * multiplier;
  42. value = value < 0.6 ? 0 : Mathf.CeilToInt(value);
  43. text.text = $"{(int)value}{suffix}";
  44. }
  45. else if(textType == TextType.CurrentMax)
  46. {
  47. float value = slider.value;
  48. float max = slider.maxValue;
  49. text.text = $"{(int)value}{separator}{(int)max}";
  50. }
  51. if(hideEmptyFill)
  52. {
  53. if((int)slider.value == 0 && slider.fillRect.gameObject.activeSelf)
  54. Timer.ExecuteRealTime(20, () => slider.fillRect.gameObject.SetActive(false));
  55. else if(!slider.fillRect.gameObject.activeSelf)
  56. Timer.ExecuteRealTime(20, () => slider.fillRect.gameObject.SetActive(true));
  57. }
  58. }
  59. }
  60. }