- Home /
Remove Objects from a List via script
I'm working a quiz game and i added a category(enum) to every question and now i wanted to let the player decide which category he wants to play.
i tried:
for (int i = 0; i < unansweredFacts.Length; i++)
{
if ((int)unanswerdFacts[i].category != setCategory)
{
unansweredFacts.removeAt(i);
}
}
but this code doesn't work
Answer by FlaSh-G · Aug 12, 2017 at 12:32 PM
In a list, when you delete an item at a position, all the following items move down one index so there's no empty space. So when you have this:
[ a, b, c, d, e ]
and remove at [2], you get
[ a, b, d, e ]
Which means that i, your counter, is pointing on "d" after the deletion. Then, the loop continues with i++
, moving it to "e". The result: "d" isn't even checked.
The solution:
for (int i = 0; i < unansweredFacts.Length; i++)
{
if ((int)unanswerdFacts[i].category != setCategory)
{
unansweredFacts.removeAt(i);
i--;
}
}
or, if you like this more (it's a question of taste):
for (int i = 0; i < unansweredFacts.Length;) // no i++ here
{
if ((int)unanswerdFacts[i].category != setCategory)
{
unansweredFacts.removeAt(i);
}
else
{
i++;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
AddComponent Loop 1 Answer
Use a enum from another script 2 Answers
Changing enum values with int label 1 Answer