BtnGroupSelector.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using TMPro;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. namespace AppUI.Util.Group
  8. {
  9. public class BtnGroupSelector : MonoBehaviour
  10. {
  11. Action<int> onSelect;
  12. int currentIndex = -1;
  13. public void Init(
  14. string[] texts,
  15. int selectIndex,
  16. Action<int> callback)
  17. {
  18. currentIndex = selectIndex;
  19. onSelect = callback;
  20. Render(texts);
  21. for (int i = 0; i < transform.childCount; i++)
  22. {
  23. int index = i;
  24. var btn =
  25. transform.GetChild(i)
  26. .GetComponentInChildren<Button>();
  27. btn.onClick.RemoveAllListeners();
  28. btn.onClick.AddListener(() =>
  29. {
  30. Select(index);
  31. });
  32. }
  33. }
  34. void Select(int index)
  35. {
  36. if (currentIndex == index)
  37. return;
  38. currentIndex = index;
  39. onSelect?.Invoke(index);
  40. RefreshState();
  41. }
  42. void Render(string[] texts)
  43. {
  44. for (int i = 0; i < transform.childCount; i++)
  45. {
  46. var item =
  47. transform.GetChild(i)
  48. .GetComponent<SelectItem>();
  49. item.SetData(
  50. texts[i],
  51. i == currentIndex);
  52. }
  53. }
  54. void RefreshState()
  55. {
  56. for (int i = 0; i < transform.childCount; i++)
  57. {
  58. var item =
  59. transform.GetChild(i)
  60. .GetComponent<SelectItem>();
  61. item.SetData(
  62. item.GetComponentInChildren<TMP_Text>().text,
  63. i == currentIndex);
  64. }
  65. }
  66. }
  67. }