- Home /
Slider snap to interval
Is there anyway to make set values for a slider that when slid it will snap to those values? For example say I have a slider with a value of 0 to 10. Can I have 10 values in-between so when you slide it, it snaps to 1 then 2 then 3, ect. Instead of being able to freely slide it to whatever value you want.
Answer by Loius · Oct 02, 2010 at 03:34 AM
You could cast the result of .Slider to an int, which would lock it to integers. Or you could go more fancy and write your own locking code -
int result = GUI.Slider(blah);
if ( result < 10 ) result = 0; else if ( result < 20 ) result = 10;
etc..
Answer by $$anonymous$$ · Feb 14, 2018 at 12:37 AM
Here's a versatile piece of code to round to any interval. You can include this in a function that gets called when the slider's value is changed.
float value = slider.value;
float interval = 0.2f; //any interval you want to round to
value = Mathf.Round(value / interval) * interval;
slider.value = value;
this is the correct answer, made a class and simply add this to your Slider UI:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class SliderValueSnap : MonoBehaviour
{
public float snapInterval = 5; //any interval you want to round to
private Slider sliderUI;
void Start()
{
sliderUI.onValueChanged.AddListener(delegate { ShowSliderValue(); });
ShowSliderValue();
}
public void ShowSliderValue()
{
float value = sliderUI.value;
value = Mathf.Round(value / snapInterval) * snapInterval;
sliderUI.value = value;
}
}
Your answer
Follow this Question
Related Questions
Vector3 distance to fill slider. 2 Answers
Adjust Brightness Screen 3 Answers
make checkpoint in sliderbar 0 Answers
Slider UI rotate image/sprite 1 Answer
Fire time interval problem? 1 Answer