| | 1 | | using UnityEngine; |
| | 2 | | using UnityEngine.UI; |
| | 3 | |
|
| | 4 | | /// <summary> |
| | 5 | | /// Perform toggle action for all IToggleBehaviour components attached to the gameObject |
| | 6 | | /// when UI toggle state is changed |
| | 7 | | /// </summary> |
| | 8 | | [RequireComponent(typeof(Toggle))] |
| | 9 | | public class UIOnToggleUpdater : MonoBehaviour |
| | 10 | | { |
| | 11 | | private Toggle toggle; |
| | 12 | |
|
| | 13 | | private IUIToggleBehavior[] toggleBehaviours; |
| | 14 | |
|
| | 15 | | protected void Awake() |
| | 16 | | { |
| 705 | 17 | | toggleBehaviours = GetComponents<IUIToggleBehavior>(); |
| | 18 | |
|
| 705 | 19 | | if (toggleBehaviours.Length == 0) |
| 0 | 20 | | Destroy(this); |
| | 21 | |
|
| 705 | 22 | | toggle = GetComponent<Toggle>(); |
| | 23 | |
|
| 705 | 24 | | PerformToggleBehaviour(toggle.isOn); |
| | 25 | |
|
| 705 | 26 | | toggle.onValueChanged.AddListener(PerformToggleBehaviour); |
| 705 | 27 | | } |
| | 28 | |
|
| | 29 | | private void OnDestroy() => |
| 705 | 30 | | toggle.onValueChanged.RemoveListener(PerformToggleBehaviour); |
| | 31 | |
|
| | 32 | | private void PerformToggleBehaviour(bool isOn) |
| | 33 | | { |
| 5632 | 34 | | foreach (IUIToggleBehavior toggleBehavior in toggleBehaviours) |
| 1798 | 35 | | toggleBehavior.Toggle(isOn); |
| 1018 | 36 | | } |
| | 37 | | } |