I’m having trouble trying to convert from string to int in unity. It keeps giving me FormatExceptions.
In my editor i have dragged a reference to the text object in my scene to the script itself. Its type is TMP_Text. Lets call textObject. When calling the ParseString Method i pass in the textObject.text property since its the string i’m looking for. I have confirmed this with a Debug.Log (which works fine btw)
What i’ve tried so far:
private static int ParseString(string dayText)
{
int num = 0;
num = int.Parse(dayText);
return num;
}
This throws a FormatException
private static int ParseString(string dayText)
{
int num = 0;
if int.TryParse(dayText, out num);
return num;
throw new System.ArgumentException("Argument must be a number");
}
Here the TryParse returns false and the ArgumentException is thrown.
private static int ParseString(string dayText)
{
dayText = string.Format("{0}", dayText);
int num = 0;
num = System.Convert.ToInt32(dayText);
return num;
throw new System.ArgumentException("Argument must be a number!");
}
Here I get another FormatException.
private static int ParseString(string dayText)
{
dayText = string.Format("{0}", dayText);
int num = 0;
if (int.TryParse(dayText, out num);
return num;
throw new System.ArgumentException("Argument must be a number!");
}
I tried using the formatting method which didn’t work. Still throws the ArgumentException.
private static int ParseString(string text)
{
string temp = "1";
temp = temp + text;
int num = 0;
if (int.TryParse(dayText, out num);
return num;
throw new System.ArgumentException("Argument must be a number!");
}
I tried some concatination. Still returns false and throws the ArgumentException.
And for the record i tried all the above methods with each of the converting Methods. the other two throws a FormatException instead of the ArgumenteException i wrote.
Additionally i made a test script and tried some of the same conversion using that TMP_Text reference again, but a completely new one, seperate from anything that was already in the scene. Still no conversion on the object, but works fine when i define my own strings somewhere in the class or even change them at runtime with a [SerializedField] private string text;
I tried passing in my own string defined in the method where i use ParseString() and it works as expected. I did the same, defining a field and a property in the class.
I’m starting to believe there is no way around this and i have to find an alternative.
It might just be a problem