Reputation: 67
I'm making a small game in unity that requires the input of the player for a small calculation. However, the input number is in a string format and requires to be converted into an integer for calculation. I'm using the Unity Input Field with TextMesh Pro for player input.
Here's the method that executes once the "Calculate" button is clicked.
The CalcObjects
array hold TextMeshProUGUI's from the input fields. The second index holds the answer after calculation.
public void Calculate()
{
string answer = "";
string velocity = CalcObjects[0].text;
Debug.Log(Convert.ToInt32(velocity.Trim()));
CalcObjects[2].text = answer;
}
The error message is:
FormatException: Input string was not in a correct format.
Any ideas on how to fix this?
Upvotes: 0
Views: 2165
Reputation: 471
Just had this issue for a few hours fun, turns out TMPro inserts white space characters that will always return a non valid conversion, whether you try Int32.TryParse or not.
The solution is to step through your string and throw out chars that aren't valid digits.
This function works for me, but it assumes the number is positive, and ignores formats, commas etc Use at your own risk, but it got me out of trouble!
public static int IntParseFast(string value)
{
int result = 0;
for (int i = 0; i < value.Length; i++)
{
char letter = value[i];
if (letter > 47 && letter < 58) { result = 10 * result + (letter - 48); }
}
return result;
}
Upvotes: 0
Reputation: 67
Found the answer, have to admit that it was rather lazy on my part.
I was trying to directly edit the 'text' component of the input fields so instead of using TextMeshProUGUI's
I should have used TMP_InputField
variables.
Set the content type to IntegerNumber
as @derHugo suggested, and then used the following code:
public void Calculate()
{
int answerInt = 0;
answerInt = Convert.ToInt32(CalcObjects[0].text) / Convert.ToInt32(CalcObjects[1].text);
Debug.Log(answerInt);
}
Thanks for helping me guys, as you can tell, I'm more of a beginner.
Upvotes: 1
Reputation: 90580
Regardless of what exactly the string is you are passing in when you get the error I would rather use Int32.TryParse
to catch invalid inputs
public void Calculate()
{
var answer = "";
var velocity = CalcObjects[0].text.Trim();
if(Int32.TryParse(velocity, out var intValue))
{
Debug.Log(intValue);
CalcObjects[2].text = answer;
}
else
{
Debug.LogWarning($"Invalid input: \"{velocity}\"");
CalcObjects[2].text = "";
}
}
you could btw further avoid any errors already one step before here by setting a specific contentType
for your input field:
private void Awake()
{
CalcObjects[0].contentType = ContentType.IntegerNumber;
}
so a user can't even insert anything that is not an integer value
Upvotes: 0