| | 1 | | using TMPro; |
| | 2 | | using UnityEngine; |
| | 3 | | using UnityEngine.UI; |
| | 4 | | using static UnityEngine.UI.Toggle; |
| | 5 | |
|
| | 6 | | public interface ISectionToggle |
| | 7 | | { |
| | 8 | | /// <summary> |
| | 9 | | /// Event that will be triggered when the toggle is selected. |
| | 10 | | /// </summary> |
| | 11 | | ToggleEvent onSelect { get; set; } |
| | 12 | |
|
| | 13 | | /// <summary> |
| | 14 | | /// Get the toggle info. |
| | 15 | | /// </summary> |
| | 16 | | /// <returns>Model with all the toggle info.</returns> |
| | 17 | | SectionToggleModel GetInfo(); |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Set the toggle info. |
| | 21 | | /// </summary> |
| | 22 | | /// <param name="model">Model with all the toggle info.</param> |
| | 23 | | void SetInfo(SectionToggleModel model); |
| | 24 | |
|
| | 25 | | /// <summary> |
| | 26 | | /// Invoke the action of selecting the toggle. |
| | 27 | | /// </summary> |
| | 28 | | void SelectToggle(); |
| | 29 | | } |
| | 30 | |
|
| | 31 | | public class SectionToggle : MonoBehaviour, ISectionToggle |
| | 32 | | { |
| | 33 | | [SerializeField] private Toggle toggle; |
| | 34 | | [SerializeField] private TMP_Text sectionText; |
| | 35 | | [SerializeField] private Image sectionImage; |
| | 36 | |
|
| | 37 | | public ToggleEvent onSelect |
| | 38 | | { |
| 110 | 39 | | get { return toggle?.onValueChanged; } |
| | 40 | | set |
| | 41 | | { |
| 267 | 42 | | toggle?.onValueChanged.RemoveAllListeners(); |
| 267 | 43 | | toggle?.onValueChanged.AddListener((isOn) => |
| | 44 | | { |
| 45 | 45 | | if (isOn) |
| 45 | 46 | | value?.Invoke(isOn); |
| 45 | 47 | | }); |
| 267 | 48 | | } |
| | 49 | | } |
| | 50 | |
|
| | 51 | | public SectionToggleModel GetInfo() |
| | 52 | | { |
| 4 | 53 | | return new SectionToggleModel |
| | 54 | | { |
| | 55 | | icon = sectionImage.sprite, |
| | 56 | | title = sectionText.text, |
| | 57 | | onSelect = onSelect |
| | 58 | | }; |
| | 59 | | } |
| | 60 | |
|
| | 61 | | public void SetInfo(SectionToggleModel model) |
| | 62 | | { |
| 267 | 63 | | if (model == null) |
| 0 | 64 | | return; |
| | 65 | |
|
| 267 | 66 | | if (sectionText != null) |
| 267 | 67 | | sectionText.text = model.title; |
| | 68 | |
|
| 267 | 69 | | if (sectionImage != null) |
| | 70 | | { |
| 267 | 71 | | sectionImage.enabled = model.icon != null; |
| 267 | 72 | | sectionImage.sprite = model.icon; |
| | 73 | | } |
| | 74 | |
|
| 267 | 75 | | onSelect = model.onSelect; |
| 267 | 76 | | } |
| | 77 | |
|
| | 78 | | public void SelectToggle() |
| | 79 | | { |
| 0 | 80 | | if (toggle == null) |
| 0 | 81 | | return; |
| | 82 | |
|
| 0 | 83 | | toggle.isOn = true; |
| 0 | 84 | | } |
| | 85 | |
|
| | 86 | | private void OnDestroy() |
| | 87 | | { |
| 433 | 88 | | if (toggle != null) |
| 433 | 89 | | toggle.onValueChanged.RemoveAllListeners(); |
| 433 | 90 | | } |
| | 91 | | } |