Created
August 6, 2020 11:55
-
-
Save AleksaDjordjic/b713bc9d61eacda9d7f4d0c1292a0b55 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UI; | |
using static UnityEngine.UI.InputField; | |
public class NumberSelect : MonoBehaviour | |
{ | |
[Header("References")] | |
[SerializeField] InputField input; | |
[SerializeField] Button increaseButton; | |
[SerializeField] Button decreaseButton; | |
[Header("Settings")] | |
public int maxValue; | |
public int minValue; | |
public int Value | |
{ | |
get | |
{ | |
int output = minValue; | |
int.TryParse(input.text, out output); | |
return output; | |
} | |
set | |
{ | |
if(value < minValue) | |
{ | |
input.text = minValue.ToString(); | |
} | |
else if (value > maxValue) | |
{ | |
input.text = maxValue.ToString(); | |
} | |
else | |
{ | |
input.text = value.ToString(); | |
} | |
} | |
} | |
public OnChangeEvent OnValueChanged | |
{ | |
get { return input.onValueChanged; } | |
protected set {} | |
} | |
int lastValue; | |
void Awake() | |
{ | |
input.contentType = ContentType.IntegerNumber; | |
} | |
void Start() | |
{ | |
ValidateText(); | |
lastValue = int.Parse(input.text); | |
} | |
void OnEnable() | |
{ | |
input.onValueChanged.AddListener(OnInputValueChanged); | |
increaseButton.onClick.AddListener(Increase); | |
decreaseButton.onClick.AddListener(Decrease); | |
} | |
void OnDisable() | |
{ | |
input.onValueChanged.RemoveListener(OnInputValueChanged); | |
increaseButton.onClick.RemoveListener(Increase); | |
decreaseButton.onClick.RemoveListener(Decrease); | |
} | |
bool ValidateText() | |
{ | |
if(string.IsNullOrEmpty(input.text)) | |
{ | |
input.text = minValue.ToString(); | |
return false; | |
} | |
else return true; | |
} | |
void OnInputValueChanged(string newInput) | |
{ | |
if(ValidateText()) | |
{ | |
Value = int.Parse(newInput); | |
} | |
} | |
void Increase() | |
{ | |
Value += 1; | |
} | |
void Decrease() | |
{ | |
Value -= 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment