ToggleGroup3D.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. /// <summary>
  6. /// Manages multiple ToggleButtons. When one requests a push, it causes the current toggled button to be untoggled
  7. /// before calling that button's toggle method. Similar to UI.ToggleGroup for Unity's 2D canvases.
  8. /// </summary>
  9. public class ToggleGroup3D : MonoBehaviour
  10. {
  11. /// <summary>
  12. /// List of all toggle buttons within the group.
  13. /// </summary>
  14. [Tooltip("List of all toggle buttons within the group. ")]
  15. public List<ToggleButton> buttons = new List<ToggleButton>();
  16. /// <summary>
  17. /// Index of the currently toggled button.
  18. /// </summary>
  19. [Tooltip("Index of the currently toggled button.")]
  20. public int toggledIndex = 0;
  21. /// <summary>
  22. /// Whether to call the toggle action of the button toggledIndex in Start().
  23. /// Usually best to set to true, but you may want to set its toggle effects elsewhere for timing reasons.
  24. /// </summary>
  25. [Tooltip("Whether to call the toggle action of the button toggledIndex in Start(). " +
  26. "Usually best to set to true, but you may want to set its toggle effects elsewhere for timing reasons.")]
  27. public bool toggleAtStart = false;
  28. // Use this for initialization
  29. void Start ()
  30. {
  31. for(int i = 0; i < buttons.Count; i++)
  32. {
  33. buttons[i].toggleGroup = this;
  34. buttons[i].index = i;
  35. }
  36. if(toggleAtStart) ToggleNewButton(toggledIndex);
  37. }
  38. /// <summary>
  39. /// Changes the toggle index to a new button, calling all relevant toggle/untoggle methods in all buttons.
  40. /// </summary>
  41. public void ToggleNewButton(int index)
  42. {
  43. if(buttons.Count <= index)
  44. {
  45. throw new System.Exception("Called ToggleNewButton with index " + index + " but there are only " + buttons.Count + " buttons registered.");
  46. }
  47. for(int i = 0; i < buttons.Count; i++)
  48. {
  49. buttons[i].ChangeToggleState(i == index);
  50. }
  51. toggledIndex = index;
  52. }
  53. }