1
\$\begingroup\$
GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        for(int i = 0; i < allDoors.Count; i++)
        {
            if(allDoors[i].transform.parent.name != "Wall_Door_Long_01" && allDoors[i].transform.parent.name != "Wall_Door_Long_02")
            {
                allDoors.RemoveAt(i);
            }
        }

        foreach(GameObject door in allDoors)
        {
            Debug.Log("Door Parent : " + door.transform.parent);
        }

If it's not "Wall_Door_Long_01" and not "Wall_Door_Long_01" then remove the item from the list.

After that when I'm doing a loop on the allDoors again and debug log the parents I see that some of the parents are not "Wall_Door_Long_01" and not "Wall_Door_Long_02" but after removing they all should be only "Wall_Door_Long_01" or "Wall_Door_Long_02"

Maybe the comparison is wrong ?

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

Once you remove at index N, the next value in the list will take it place, and it will be skipped in verification, because you increment an index.

Solution 1. Firstly create a list of items to be removed, and then use it as source for removal.

    List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();
    List<GameObject> toRemove = new List<GameObject>();
        for(int i = 0; i < allDoors.Count; i++)
        {
            if(allDoors[i].transform.parent.name != "Wall_Door_Long_01" && allDoors[i].transform.parent.name != "Wall_Door_Long_02")
            {
                toRemove.Add(allDoors[i]);
            }
        }
        foreach(var it in toRemove)
        {
             allDoors.Remove(it);
        }

Solution 2. Right after removing at index N, decrement index variable to check the new element at this index again next loop iteration.

allDoors.RemoveAt(i);
i--;
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could iterate the list as well backwards with for(int i = allDoors.Count - 1; i >=0 ; i--) \$\endgroup\$
    – Zibelas
    Feb 19, 2020 at 8:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .