- Home /
Saving only Integers in an inputfield via code
I need to save integers in a variable through inputfield but i dont know how and i have searched all over the internet but i cant find any solution to this problem here is an example of what i mean
public var number : int; public var inputField : InputField;
function Start() { inputField = GetComponent(InputField); }
function Update() { number = inputField.text; //i cant do that because its not possible to save string into an int variable but thats basically what i mean.. saving Integers into an int vriable from an InputField...
i have no clue how to do.. would like to get some help from you guys :)
}
Answer by siaran · Mar 24, 2015 at 01:43 PM
You need to parse your string to an int. Lucky for you, you probably won´t have to write code to do that all yourself, here is a method I found for javascript:
i want pepole to input only numbers into an inputField box and then it will save the number they put in an int variable.
will this function help me to do that?
...it converts a string (what you get in your input) to an int (what you want). If you want to make sure people only put ints in your input field, you'll have to check if what they give is an int. parseInt returns NaN when the first character in the string is not an int, so you could write something like
//store field input
string fieldInput;
//int
int someInt;
fieldInput = inputField.text;
if(!isNaN(parseInt(fieldInput)){
someInt = parseInt(fieldInput);
//do stuff with someInt
}else{
//do something to tell user that his input is invalid
}
You can setup your InputField component to only accept numbers, you don't need to check that in code. Look at the "Content type" property of the InputField, one of the options is "Integer number".
Your answer
![](https://koobas.hobune.stream/wayback/20220613191043im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Masked InputField on Unity UI 4 Answers
How can I block Copy Paste from Input Field? 3 Answers
Input fields act abritrarily 0 Answers
Android Keyboard Stuck / Won't Hide? 1 Answer