- Home /
Duplicate Question
Allow only numbers to a textfield, and make it an int.
How do I use a textfield that can only have numbers typed into it? Also, I need all the things typed in to be converted from a string, to an int.
I want a user to be able to type a number between 1 and 70 into the textfield. I will then feed that number into a loop which will determine how many times the prefab is instantiated.
I've searched many times (MANY) aand couldn't find anything.
Thanks in advance!
convert to int should be this :
var intvariable : int = parseInt(stringvariable);
and for checking the characters i don't have a good idea but i think you need a loop like this :
for (var i = 0; i < stringvariable.Length; i++)
{ }
then compare every character with numbers (a array of 0-9) . that should be another loop ;) i hope it helps you
Answer by code_warrior · Jan 02, 2015 at 07:12 PM
Hi there
Its even simpler!
Assuming your using the new UI!
Just change your Inspector to Debug Mode and Set Integer or Float as the Validation type.

The string can be easily parsed to int by calling int.Parse(yourString). After you've passed it you could also check if its within your range.
code_warrior
Similarly, InputField.ContentType can be set in the inspector in Normal $$anonymous$$ode. (I just tried on Unity 2018.3.)
https://docs.unity3d.com/ScriptReference/UI.InputField.ContentType.html
Answer by Graham-Dunnett · Jan 02, 2015 at 06:31 PM
In your OnGUI() code look at the string which is being entered into the TextField, and remove any characters that are not digits.
How would I do that? Also, how can I convert the string content into an int? I need it to be compatible with a loop int.
Answer by Eric5h5 · Jan 02, 2015 at 07:16 PM
This has been answered many times; just doing a search for "textfield int" turned up a bunch of answers. http://answers.unity3d.com/questions/18736/restrict-characters-in-guitextfield.html Use Int.Parse to convert a string to an int.
Follow this Question
Related Questions
GUI.Textfield to int ? 2 Answers
How To send Email with C# on Unity 3D 4.1.2? 8 Answers
I need help with water as a whole 1 Answer
How to disable Shadows Camera like picture? Please Help me. Thanks! 0 Answers