- Home /
Unknown remaining objects after removing and destroying from list and parent game objects
Ok, so... I have a couples of game objects, I put them into a list for processing in the game, and once the processing is done at the end of the level, the whole list will be cleared to renew the level. Level 1 was fine, but from level 2 there were some game objects still remained after destroying and removing, both from the list and their parents. I've printed their names, and found out that those objects belonged to the last level, not the current one. In the hierachy, the number of objects was exactly as expected, except that the child object started from 1, not 0, and the parent objects' childCount were all plus 1. I have no idea how this happened. I think it must be something about threads, which I don't know much about. Do you guys have any ideas of what's going on? Thanks a lot, and sorry for my bad English!
Here is my code for clearing the scene:
public void ClearScene()
{
btnDone.SetActive(false);
List<GameObject> listToy = GamePlayer.instance.listToy;
// Destroy objects from the list
for (int i = 0; i < listToy.Count; i++)
{
Destroy(listToy[i]);
}
listToy.Clear();
//
Transform upper = shelf.transform.GetChild(0);
Transform lower = shelf.transform.GetChild(1);
int upperCount = upper.childCount;
int lowerCount = lower.childCount;
// Rescan parents and destroy again
for (int i = 0; i < upperCount; i++)
{
print(upper.GetChild(i).name);
Destroy(upper.GetChild(i).gameObject);
}
for (int i = 0; i < lowerCount; i++)
{
print(lower.GetChild(i).name);
Destroy(lower.GetChild(i).gameObject);
}
//
// Print list count and child count after deletion
print("List count: " + listToy.Count);
print("Upper shelf count: " + upperCount + "\t" + "Lower shelf count: " + lowerCount);
//
// Unrelevant
for (int i = 0; i < gridButton.transform.childCount; i++)
{
Destroy(gridButton.transform.GetChild(i).gameObject);
}
//
}
The number of children that your upper/lower Transforms have is changing within your loops (because you are destroying children). One way to handle this (the way with the smallest code change) would be to go backwards through the children, for example from (upperCount-1) to zero, rather than from zero to (upperCount-1).
Interesting issue! At first look at the code, it should work as expected, destroying all the objects in listToy
then clearing it.
One thing that comes to my $$anonymous$$d is that maybe the "toys" are destroyed, but as the manual and this answer says, actual destruction only happens at the end of the current frame. Could that cause an issue?
What happens if you print upperCount
and lowerCount
before doing the rescan and destroy again part?
Your answer
Follow this Question
Related Questions
List That Won't Remove The Last Two Elements 3 Answers
Removing objects from a list in C# 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Removing a class object from a list(.remove not working) C# 1 Answer