Well, I was making a true/false quiz game and I decided to load the questions from a text file with a fancy back name(.questionbank). I wrote this nice piece of code
//initialize from .txt
List<Question> loadedQuestions = new List<Question>();
StreamReader sr = new StreamReader(Application.dataPath + "/" + BankName + ".questionbank",Encoding.Unicode);
TheString = sr.ReadToEnd();
if (TheString != null)
List<string> singleLines = TheString.Split('#').ToList();
int X = 0;
foreach (string item in singleLines)
if (item[X].Equals("/") && item[X+1].Equals("/") && item[X+2].Equals("/"))
string fact = item.Substring(X);
_isTrue = true;
_isTrue = false;
Question question = new Question();
question.fact = fact;
question.isTrue = _isTrue;
X = X+1;
} while (TheString != null);
but it gave me this error: IndexOutOfRangeException: Array index is out of range. and said the problem was on this line: if (item[X].Equals("/") && item[X+1].Equals("/") && item[X+2].Equals("/"))
I have no idea what the problem is... Any help is appriciated!
Answer by tanoshimi
6 days ago
It would be helpful to know what the structure of your question file is, but your logic looks..... funky....
You're looping though every item in singleLines (which in turn is a list of items separated by a # from your questionbank file).
Then, you're looking whether the nth, n+1th, and n+2th character are all forward slashes and creating a question accordingly.
Because you increment X on every iteration of the loop, by the time you're loading the 100th question, say, you're checking whether the 100th, 101st, and 102nd character of that question are all forward slashes. Is that really what you meant?
The error message is saying that it's encountered a question that simply doesn't have enough characters to access the index requested.
If I had to guess, did you mean for line 31 to always check the first three characters of every question instead?
if (item.Equals("/") && item.Equals("/") && item.Equals("/"))
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users navigate the site we have posted a site navigation guide.
If you are a new user to Unity Answers, check out our FAQ for more information.
Make sure to check out our Knowledge Base for commonly asked Unity questions.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
Answers and Comments
132 People are following this question.
ERROR 15,36 An object reference is required to access non-static members UnityEngine.Transform.Find(string)
C# If string is equal to any in array
Assign values to array elements
How to see if a string in a string array is equal to a normal string in C#?
need help in randomising array