Can't parse an INT from text in a TextMeshPro Input Field

This is a weird error. I have a TextMeshPro input field that has a content type of Integer to ensure only integers are entered. When I do int.Parse() it throws the “not in a correct format” error, even though it’s an integer.

I enter something like 123 into the text field and it throws the error. If I test the int.Parse(“123”) it works fine, but if I use the text from the input field it doesn’t.

Does anyone know what’s up?

Example of the code:

string inputText = tmProInput.text.ToString(); // Enter 123 as the input, only integers are allowed
Debug.Log("Input text: *" + inputText + "*");
int inputInt = int.Parse(inputText); // This Fails
int inputInt = int.Parse("123"); // This Works

This was a really good idea:

Debug.Log("Input text: *" + inputText + "*");

Can you tell us what it printed?
Another good idea would be:

Debug.Log($"Input string length is {inputText.Length}");

It prints out 123 That’s why I’m so confused.

And what does it print out for length of the string? I’d wager probably 4 or more. You may have an invisible character in there.

Yup, it’s 4, but not sure how to check or get rid of the extra character, no idea what is it.

You can use Regex to filter the string to only integers, my guess is that the last character is some end-of-line character.

         var matches = Regex.Matches(str1, @"\d+");
         foreach(var match in matches){
            str2 += match;
         }
         val = int.Parse(str2);

Stolen from somewhere on the internet.

Yup the end of line is. I looped through and it has some odd character that doesn’t print, even though it’s set to “Single Line”. I just Substring the text to the length minus 1 and it worked. I had another input field it was doing the same thing to.

I would recommend using https://docs.microsoft.com/en-us/dotnet/api/system.string.trim?view=net-7.0 instead.