- Home /
.TXT File loading error
I'm having an error with this script, which should load a .txt file, read in each line, and seperate that line into 7 variables. Have a look:
StreamReader sr = new StreamReader(Application.dataPath + "/" + "model.3dl"); string fileContents = sr.ReadToEnd(); sr.Close();
string[] lines = fileContents.Split('\n');
for (int j = 0;j<lines.Length;j++) {
string[] loadData = new string[7];
loadData = lines[j].Split(':');
Debug.Log(loadData[1]);
}
Now, whenever I run the game, I get this error:
IndexOutOfRangeException: Array index is out of range.
Which points me to the Debug.Log line in the above script. Said script looks fine to me, perhaps I just need another pair of eyes to point out the problem. It's somewhat derived from the helpful answer to this question, with the exception that I converted it from JS to C#.
If the solution is biting me on the nose, please don't hesitate to tell me. If it's not so obvious, tell me anyways. I just want it to work. :)
Answer by yoyo · Feb 06, 2011 at 04:35 AM
If you hit a line with no colons in it then Split will return an array of length 1, in which case loadData[1] will be off the end of the (0-based) array. String.Split return a new array, so there's no need to initialize loadData.
Okay, thanks for pointing that out. It was partially that, and partially the fact that I should have, in the for loop, set to run while j
< length should be fine. You might get an extra blank line at the end, but your parsing code should be able to handle it, and it wouldn't be the reason for the out of bounds error.
Your answer
Follow this Question
Related Questions
Try/Catch block stops exception from happening 0 Answers
How to prevent StreamReader from hanging when reading from a socket 1 Answer
IndexOutOfRangeException 1 Answer
IndexOutOfRangeException only on iOS! Android / PC is ok!! 1 Answer
IndexOutOfRangeException when naming an animator parameter 0 Answers