| | 1 | | using UnityEngine; |
| | 2 | | using UnityEngine.UI; |
| | 3 | | using UnityEngine.Events; |
| | 4 | |
|
| | 5 | | public class SpinBoxPresetted : MonoBehaviour |
| | 6 | | { |
| | 7 | | [System.Serializable] |
| | 8 | | public class OnValueChanged : UnityEvent<int> { } |
| | 9 | |
|
| | 10 | | [Header("References")] |
| | 11 | | [SerializeField] TMPro.TextMeshProUGUI textLabel = null; |
| | 12 | |
|
| | 13 | | [SerializeField] Button increaseButton = null; |
| | 14 | | [SerializeField] Button decreaseButton = null; |
| | 15 | |
|
| | 16 | | [Header("Config")] |
| | 17 | | [SerializeField] string[] labels = null; |
| | 18 | |
|
| | 19 | | [SerializeField] int startingValue = 0; |
| | 20 | |
|
| | 21 | | public bool loop; |
| | 22 | | public OnValueChanged onValueChanged; |
| | 23 | |
|
| | 24 | | private int currentValue; |
| | 25 | |
|
| 0 | 26 | | public int value { get { return currentValue; } set { SetValue(value); } } |
| | 27 | |
|
| 0 | 28 | | public string label { get { return textLabel.text; } set { OverrideCurrentLabel(value); } } |
| | 29 | |
|
| | 30 | | void Awake() |
| | 31 | | { |
| 6 | 32 | | increaseButton.onClick.AddListener(IncreaseValue); |
| 6 | 33 | | decreaseButton.onClick.AddListener(DecreaseValue); |
| 6 | 34 | | SetValue(startingValue, false); |
| 6 | 35 | | } |
| | 36 | |
|
| 0 | 37 | | public void SetLabels(string[] labels) { this.labels = labels; } |
| | 38 | |
|
| | 39 | | public void SetValue(int value, bool raiseValueChangedEvent = true) |
| | 40 | | { |
| 9 | 41 | | if (value >= labels.Length || value < 0) |
| | 42 | | { |
| 2 | 43 | | return; |
| | 44 | | } |
| | 45 | |
|
| 7 | 46 | | textLabel.text = labels[value]; |
| 7 | 47 | | currentValue = (int)value; |
| 7 | 48 | | startingValue = currentValue; |
| 7 | 49 | | if (raiseValueChangedEvent) |
| 1 | 50 | | onValueChanged?.Invoke(value); |
| | 51 | |
|
| 7 | 52 | | if (!loop) |
| | 53 | | { |
| 0 | 54 | | increaseButton.interactable = value < labels.Length - 1; |
| 0 | 55 | | decreaseButton.interactable = value > 0; |
| | 56 | | } |
| 7 | 57 | | } |
| | 58 | |
|
| 0 | 59 | | public void OverrideCurrentLabel(string text) { textLabel.text = text; } |
| | 60 | |
|
| | 61 | | public void IncreaseValue() |
| | 62 | | { |
| 0 | 63 | | int newVal = currentValue + 1; |
| | 64 | |
|
| 0 | 65 | | if (newVal >= labels.Length) |
| | 66 | | { |
| 0 | 67 | | if (loop) |
| 0 | 68 | | newVal = 0; |
| | 69 | | else |
| 0 | 70 | | newVal = labels.Length - 1; |
| | 71 | | } |
| | 72 | |
|
| 0 | 73 | | SetValue(newVal); |
| 0 | 74 | | } |
| | 75 | |
|
| | 76 | | public void DecreaseValue() |
| | 77 | | { |
| 0 | 78 | | int newVal = currentValue - 1; |
| | 79 | |
|
| 0 | 80 | | if (newVal < 0) |
| | 81 | | { |
| 0 | 82 | | if (loop) |
| 0 | 83 | | newVal = labels.Length - 1; |
| | 84 | | else |
| 0 | 85 | | newVal = 0; |
| | 86 | | } |
| | 87 | |
|
| 0 | 88 | | SetValue(newVal); |
| 0 | 89 | | } |
| | 90 | | } |