Skip to content

Instantly share code, notes, and snippets.

@nicetrysean
Last active July 28, 2017 06:56
Show Gist options
  • Save nicetrysean/db6d8b99303e44278020caaaf30896f9 to your computer and use it in GitHub Desktop.
Save nicetrysean/db6d8b99303e44278020caaaf30896f9 to your computer and use it in GitHub Desktop.
Script for both TextInput and Slider UnityUI
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