- Home /
text field - inputting numbers only
hey I am looking for a way to input numbers to a text field - or any other way do the following:
there's a place where a player can click and input a number. from between 0-300
the field will obviously have to ignore any letters entered.
Answer by Mike 3 · Dec 28, 2010 at 01:18 PM
Off the top of my head, something like this should do it, where you could change int to float all three times if you didn't want integer values:
var num : int = 0;
function OnGUI() { var text = GUI.TextField(Rect(50, 50, 200, 50), num.ToString()); var temp : int = 0; if (int.TryParse(text, temp)) { num = Mathf.Clamp(0, temp); } else if (text == "") num = 0; }
Thanks, that solves the multiple character issue. It still doesn't accept negative number strings but I have an ugly hacked work around for that for now. What I don't understand is where I have indicated in any way that this is an int only text field. Why doesn't it accept alphas?
That code won't actually work (aside from the syntax error). The text
variable will always be "0" and the textfield won't accept any input, since it's just getting the value from num.ToString, which logically can't change since there's no way for the user to actually input any text. It's better to block unwanted characters entirely; see my answer here.
many times I get to this Q when I searching this but right now I've managed to figure out something more:
GUILayout.BeginHorizontal();
GUILayout.Label("size of Hall " + somefloat);
somefloat = GUILayout.HorizontalScrollbar((int)somefloat,0.01f, 0f, 300.1f,GUILayout.Width(50));
GUILayout.EndHorizontal();
have fun coding ;)
it's int in the end ;)
@Eric5h5 I$$anonymous$$O $$anonymous$$ike 3's solution is better in this case because it guarantees that some stray forgotten character can't get through and create an invalid Int. Not sure how you were reading it because it does work; it accepts any input that can be parsed as an int and rejects all else.