Unity Canvas: Double Slider

Unity Canvas: Double Slider

A Double Slider Canvas control implementation in Unity to select a range of values.

A few years ago I was working on a mobile app that required a slider with a double input.

This type of sliders allows the user to select a range by selecting both the min and the max values.

Unity doesn’t have this type of control so I had to implement a custom one.

But, since Unity Slider already deals with a lot of stuff that I would also need (min and max values, whole numbers, callbacks, etc), the best way was to combine the existing slider components to create a slider for the min value and another for the max.

Now, to make this seem like their working together, I had to remove the fill area from each one of them and implement my own. And this is basically the only thing different from the original ones.

The min slider will control the start of the fill area, and the max slider will control the end.

And basically all the magic it’s in these two small functions. They adapt the fill area whenever either the min or the max values are changed.

private void MinValueChanged(float value)
{
    float offset = ((MinValue - _minValue) / (_maxValue - _minValue)) * _fillArea.rect.width;

    _fillRect.offsetMin = new Vector2(offset, _fillRect.offsetMin.y);

    if ((MaxValue - value) < _minDistance)
    {
        _sliderMin.Value = MaxValue - _minDistance;
    }

    _onValueChanged.Invoke(MinValue, MaxValue);
}
private void MaxValueChanged(float value)
{
    float offset = (1 - ((MaxValue - _minValue) / (_maxValue - _minValue))) * _fillArea.rect.width;

    _fillRect.offsetMax = new Vector2(-offset, _fillRect.offsetMax.y);

    if ((value - MinValue) < _minDistance)
    {
        _sliderMax.Value = MinValue + _minDistance;
    }

    _onValueChanged.Invoke(MinValue, MaxValue);
}

The _minDistance is a requirement that I had for my custom slider. I needed the option to mantain a min distance between the min and the max values so that the user could never select a range below that value.

And with all this, I’ve created an inspector which allows to configure the double slider:

But, it’s also possible to configure from code:

public class Example : MonoBehaviour
{
    #region Variables

    [Header("References")]
    [SerializeField] private SliderDouble _slider;

    #endregion

    private void Start()
    {
        _slider.Setup(10, 50, 25, 40);
        _slider.ValueChanged.AddListener(SliderDouble_ValueChanged);
    }

    private void SliderDouble_ValueChanged(float arg0, float arg1)
    {
        Debug.Log("Value Changed, min: " + arg0 + ", max: " + arg1);
    }
}

Check here for the source code and the example.