Int.Parse() not working

I’m pretty new to Unity and when talking to my friend, decided to make a miniature calculator than can calculate Σ using a for loop, so I can learn C# better. That’s not the hard part, however; I’m really struggling with the TMP InputFields. Your input is the parameter in the function you call, correct? I set the Content Type to integer, but it’s still returning a string, and I get “FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException (System.Boolean overflow, System.String overflowResourceKey” whenever I try to run my simple script. My code’s a mess because I have been testing out many things, such as /u200B(which is quite confusing), but can someone please check it out and tell me what I’m doing wrong? Thank you so much!

public class InputReader : MonoBehaviour
{
    private int topInput;

    public void ReadTopInput(string s)
    {
        //s = s.Replace("\u200B", "");
        topInput = int.Parse(s);
        //topInput = s.;
        Debug.Log(topInput);
    }
}

The goal is simply, for now, to log my topInput in the console. I need it to be an integer for later calculations. Thanks again!

If you use int.Parse you need to enclose it in try/catch blocks and handle all exceptions that occur.

If you are only ever interested in getting an actual number and otherwise use a default number or do nothing (as in this case), you should be using int.TryParse as this will not throw an exception and allows you to set a default value.

Since you use TMP input fields it’s also important to use the correct reference, otherwise the string will contain additional formatting characters.

3 Likes

Thank you so much! I’ll try it all out soon.