SelectionGrid.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using UnityEngine;
  3. namespace COM3D2.MeidoPhotoStudio.Plugin
  4. {
  5. public class SelectionGrid : BaseControl
  6. {
  7. private SimpleToggle[] toggles;
  8. private int selectedItemIndex;
  9. public int SelectedItemIndex
  10. {
  11. get => selectedItemIndex;
  12. set
  13. {
  14. selectedItemIndex = Mathf.Clamp(value, 0, toggles.Length - 1);
  15. foreach (SimpleToggle toggle in toggles)
  16. {
  17. toggle.value = toggle.toggleIndex == selectedItemIndex;
  18. }
  19. OnControlEvent(EventArgs.Empty);
  20. }
  21. }
  22. public SelectionGrid(string[] items, int selected = 0)
  23. {
  24. selectedItemIndex = Mathf.Clamp(selected, 0, items.Length - 1);
  25. toggles = MakeToggles(items);
  26. }
  27. private SimpleToggle[] MakeToggles(string[] items)
  28. {
  29. SimpleToggle[] toggles = new SimpleToggle[items.Length];
  30. for (int i = 0; i < items.Length; i++)
  31. {
  32. SimpleToggle toggle = new SimpleToggle(items[i], i == SelectedItemIndex) { toggleIndex = i };
  33. toggle.ControlEvent += (s, a) =>
  34. {
  35. int value = (s as SimpleToggle).toggleIndex;
  36. if (value != SelectedItemIndex) SelectedItemIndex = value;
  37. };
  38. toggles[i] = toggle;
  39. }
  40. return toggles;
  41. }
  42. public void SetItems(string[] items, int selectedItemIndex = -1)
  43. {
  44. if (selectedItemIndex < 0) selectedItemIndex = SelectedItemIndex;
  45. if (items.Length != toggles.Length)
  46. {
  47. toggles = MakeToggles(items);
  48. }
  49. else
  50. {
  51. for (int i = 0; i < items.Length; i++)
  52. {
  53. string item = items[i];
  54. toggles[i].value = i == SelectedItemIndex;
  55. toggles[i].label = item;
  56. }
  57. }
  58. SelectedItemIndex = Mathf.Clamp(selectedItemIndex, 0, items.Length - 1);
  59. }
  60. public override void Draw(params GUILayoutOption[] layoutOptions)
  61. {
  62. GUILayout.BeginHorizontal();
  63. foreach (SimpleToggle toggle in toggles)
  64. {
  65. toggle.Draw(layoutOptions);
  66. }
  67. GUILayout.EndHorizontal();
  68. }
  69. private class SimpleToggle
  70. {
  71. public int toggleIndex;
  72. public bool value;
  73. public string label;
  74. public event EventHandler ControlEvent;
  75. public SimpleToggle(string label, bool value = false)
  76. {
  77. this.label = label;
  78. this.value = value;
  79. }
  80. public void Draw(params GUILayoutOption[] layoutOptions)
  81. {
  82. bool value = GUILayout.Toggle(this.value, label, layoutOptions);
  83. if (value != this.value)
  84. {
  85. if (!value) this.value = true;
  86. else
  87. {
  88. this.value = value;
  89. ControlEvent?.Invoke(this, EventArgs.Empty);
  90. }
  91. }
  92. }
  93. }
  94. }
  95. }