- Home /
OnGUI sliders only accept float? C#
Hi.
I'd like to make an integer ('int') based GUI slider, similar to EditorGUI.IntSlider, running inside the game. I've tried GUI.HorizontalSlider, but it only allows for 'float'. How could I do that?
Thanks.
Answer by Bunny83 · Jan 29, 2013 at 10:05 AM
Just round it to "int" with Mathf.RoundToInt. EditorGUI.IntSlider does exactly the same thing ;)
int val = 0;
val = Mathf.RoundToInt(GUILayout.HorizontalSlider(val, 0, 10));
// or
val = Mathf.RoundToInt(GUI.HorizontalSlider(yourRect, val, 0, 10));
Answer by ginryu · Jul 12, 2020 at 05:45 AM
yourValue = (int)GUI.HorizontalSlider(Rect yourRect, yourvalue, 2,25); you can cast your slider output to int instead of using the Mathf class
Just casting to an int has several issues. First of all you get a 0.5 bias. So the bottom and top value has strange behaviour. You can only reach your max value when you actually hit the very last position as any lower value would be rounded down (if the max limit is positive). So in your specific example all values between 2 and 3 will round down to 2. Values between 3 and 4 round to 3 [...] and values between 24 and 25 will round to 24.
Another issue is negative numbers as casting to int will not consistently "floor" the value but always rounds towards zero. So a .24.999 will be rounded down to 24 while a -24.999 will round to -24, not -25. So if your slider range goes across zero (from a negative value to a positive value) you get a strange anomaly at zero since all values between -1 and 1 will round to zero.
Using the Round function takes care of that as it does proper midpoint rounding
Your answer
Follow this Question
Related Questions
Display actual number of bullets 1 Answer
Set Slider value but don't trigger On Value Changed 4 Answers
Horizontal slider won't work 1 Answer
Horizontal Slider with Labels 3 Answers
Distribute terrain in zones 3 Answers