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

3 Answers

3

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.

38044-validation.jpg

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 Mode. (I just tried on Unity 2018.3.) https://docs.unity3d.com/ScriptReference/UI.InputField.ContentType.html

You'll have to change the Content Type to Custom, to be able to modify the Keyboard Type

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.

This has been answered many times; just doing a search for “textfield int” turned up a bunch of answers. Restrict characters in GUI.TextField - Unity Answers Use Int.Parse to convert a string to an int.