Last active
July 28, 2017 06:56
-
-
Save nicetrysean/db6d8b99303e44278020caaaf30896f9 to your computer and use it in GitHub Desktop.
Script for both TextInput and Slider UnityUI
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
public class CompherensiveSlider : MonoBehaviour | |
{ | |
//Since we're using UnityEvent<T0> we need to implement the float type | |
[Serializable] | |
public class FloatEvent : UnityEvent<float> { } | |
public FloatEvent ValueChanged; | |
[SerializeField] //Display private variable in Inspector | |
private InputField _inputField; | |
[SerializeField] | |
private Slider _slider; | |
private float _inputFieldValue; | |
public float InputFieldValue | |
{ | |
get { return _inputFieldValue; } | |
private set | |
{ | |
_inputFieldValue = value; | |
ValueChanged?.Invoke(value); // C# 6 for use in Unity 2017.1 and above | |
} | |
} | |
void Start() | |
{ | |
//http://blogs.unity3d.com/2015/08/25/the-unity-assertion-library/ | |
Assert.IsNotNull(_inputField, "CompherensiveSlider Requires TextInput UI Component!"); | |
Assert.IsNotNull(_slider, "CompherensiveSlider Requires Slider UI Component!"); | |
//Listen to value changes, and events | |
_slider.onValueChanged.AddListener(SliderChanged); | |
_inputField.onValueChanged.AddListener(InputFieldValueChanged); | |
} | |
/// <summary> | |
/// Updates cached value as the InputField changes | |
/// </summary> | |
/// <param name="value">InputField string</param> | |
void InputFieldValueChanged(string value) | |
{ | |
float floatValue; | |
if (float.TryParse(value, out floatValue)) | |
{ | |
InputFieldValue = floatValue; | |
} | |
if(_slider.value != InputFieldValue) | |
_slider.value = InputFieldValue; | |
} | |
/// <summary> | |
/// Calls the UnityEvent to fire with the value | |
/// </summary> | |
void SliderChanged(float value) | |
{ | |
if (value == InputFieldValue) return; | |
InputFieldValue = value; | |
_inputField.text = value.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment