I have a script that puts all targets in a scene into a List, they are sorted by distance and the first one is selected by the Tab key. That part works well. It’s when one of the mobs is killed, I get an error because the List is now corrupted because I am down one mob. What is the best way to go about this, or should it be done a completely different way? I tried to re-index the targets by calling the same function, but it doesn’t seem to work.
It would be easier to figure out your problem if you were a bit more specific - how exactly does your list get corrupted? Do you get a null reference error?
If you’re removing items from the list inside of a for loop, the loop needs to run backwards from the end of the list to the beginning otherwise your iterator won’t count correctly, and you could unintentionally skip indices and/or have problems ending your loop at the right time.
//Imagine if you will, that this list has 10 enemies in it
List<GameObject> Enemies;
//Remember, loop from the end to the beginning!
for (int i = Enemies.Count - 1; i > 0; i--)
{
if (Enemies*.health < 0)*
{ //Temporarily save a reference to the enemy so we can delete it after removing it from the list GameObject tempRef = Enemies*;* //Remove reference from list Enemies.RemoveAt(i); //And finally destroy the enemy Destroy(tempRef); } }