I am trying to load a Vector2 into my game by reading it from a text file as a string and then parsing it. But when I try to load this info, I get this exception:
Format exception was unhandled.
Input string was not in a correct format.
Text file:
{X:512 Y:384}
Code:
System.IO.StreamReader objReader;
objReader = new System.IO.StreamReader(@fileName + ".txt");
string pos = objReader.ReadLine();
float aXPosition = float.Parse(pos.Substring(pos.IndexOf("X:"), pos.IndexOf(" Y")));
float aYPosition = float.Parse(pos.Substring(pos.IndexOf("Y:"), pos.IndexOf("}")));
So what I’m trying to do is reading the X and Y position from the text file. I found this technique here: http://social.msdn.microsoft.com/Forums/sk/xnagamestudioexpress/thread/fd94cfec-f1f4-4cab-aa1d-8c72b524875b
Looks pretty simple, but for some reason it’s not working for me.
Any help would be much appreciated!
It’s probably because
IndexOfgives you index of X in X: you’ve specified in parameter. Try something like this:Update
I’ve tested the code and there was also an issue with count parameter of
Substringmethod. It should indicate length of the substring and not the end index in the original string. I updated the code, so it should work correctly now.