HKI Core
UIToggleGroup.cs
Go to the documentation of this file.
1 using UnityEngine;
2 using UnityEngine.UI;
3 using UnityEngine.Events;
4 
5 namespace HKI.Core.UI
6 {
10  public class UIToggleGroup : MonoBehaviour
11  {
12  // Class
13  [System.Serializable]
14  public class OnChangeEvent : UnityEvent<int> { }
15 
16  // Public variables
17  [SerializeField] int StartId = 0;
18  [SerializeField] Button[] Buttons = null;
19  [SerializeField] GameObject[] ActiveIconGOs = null;
20 
21  [SerializeField] OnChangeEvent OnChange = new OnChangeEvent();
22 
23  // Private variables
24  GameObject[] ButtonGOs = null;
25 
26  // Awake function
27  void Awake()
28  {
29  ButtonGOs = new GameObject[Buttons.Length];
30 
31  for (int i = 0; i < Buttons.Length; i++)
32  {
33  int index = i;
34  Buttons[i].onClick.RemoveAllListeners();
35  Buttons[i].onClick.AddListener(() => { OnValueChange(index); });
36  ButtonGOs[i] = Buttons[i].gameObject;
37  ButtonGOs[i].SetActive(i != StartId);
38  ActiveIconGOs[i].SetActive(i == StartId);
39  }
40 
41  }
42 
43  // Interface function
44  public void SetTo(int index)
45  {
46  for (int i = 0; i < ButtonGOs.Length; i++)
47  {
48  ButtonGOs[i].SetActive(i != index);
49  ActiveIconGOs[i].SetActive(i == index);
50  }
51  }
52 
53  // Helper function
54  void OnValueChange(int id)
55  {
56  for(int i = 0; i < ButtonGOs.Length; i++)
57  {
58  ButtonGOs[i].SetActive(i != id);
59  ActiveIconGOs[i].SetActive(i == id);
60  }
61 
62  OnChange.Invoke(id);
63  }
64  }
65 }
This is a custom implementation of a toggle group.