- Home /
Cannot clear the Input Field from Inspector
Despite of hours of Googling but I'm still cannot figure out how to solve this problem
The problem is on the first Input Field where the number cannot be deleted when I press backspace, and I have to press backspace twice to empty the field, and on the first backspace press, it throws an Invalid Format error. I believe this has something to do with my input string format but I can't figure out why and how to fix it.
Below is the code I'm having problem with:
public void GetFirstInput()
{
Calculate();
s1 = float.Parse(a1.text, CultureInfo.InvariantCulture);
Debug.Log(s1);
}
Can anyone provide me some insights? Thanks.
I believe you have to check if the input field is not empty before calling float.Parse
Answer by Bunny83 · Sep 08, 2018 at 10:24 AM
You almost never want to use int.Parse, especially when the string comes from user data. In almost all cases you should use TryParse. TryParse returns a boolean if the parsing was successful or not. The actual parsed value is outputted to an out parameter. If the parsing fails the value is set to 0. If you want to avoid assigning 0 to your actual variable unless the user actually enters 0 you can use a temp variable like this:
int tmp;
if (int.TryParse(a1.text, NumberStyles.Integer, CultureInfo.InvariantCulture, out tmp))
s1 = tmp;
Your answer
Follow this Question
Related Questions
Masked InputField on Unity UI 4 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Help with Virtual Keyboard 0 Answers
TMP_Input Field Destroys text 2 Answers