I’m creating a D&D initiative tracker, but i can’t really find a way to convert strings to int without getting errors.
This is the line of code:
initiativeRoll = Random.Range(1, 21) + int.Parse(creature.initiative);
creature.initiative is a string and I already checked that it contains only numbers.
This is the error message i’m getting:
FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException (System.Boolean overflow, System.String overflowResourceKey) (at :0)
System.Number.ParseInt32 (System.ReadOnlySpan`1[T] value, System.Globalization.NumberStyles styles, System.Globalization.NumberFormatInfo info) (at :0)
System.Int32.Parse (System.String s) (at :0)
Please, I’m losing my mind over this.
MelvMay
December 28, 2022, 1:59pm
2
You get this when the string you pass cannot be parsed into the appropriate type, in this case an integer.
You say that but the thing you’re asking to parse it differs in that opinion.
Debugging it. You should dump the string to the console immediately before parsing it so you can verify what it’s being asked to parse.
I added this line before parsing:
Debug.Log(creature.initiative);
the console gives me a 3.
MelvMay
December 28, 2022, 2:13pm
4
Maybe there’s more than a single “3” in it then such as formatting stuff the console isn’t showing. Check the actual string yourself by attaching the debugger and inspecting it.
Also, try doing var value = int.Parse(“3”)
Presumably “creature.initiative” is an int property?
dlorre
December 28, 2022, 6:29pm
5
Try this:
int.Parse(creature.initiative.TrimEnd('\r', '\n' ));