- Home /
FindGameObjectsWithTag finds destroyed gameobjects
Hi, Im creating an algorithm for automathic level generation. In order to evaluate my algorithm I want to run it some amount of times and meassure permormance values. I also need to perform a test each time to see if the level is correct. I do this by comparing how many rooms there are in the level with how many rooms the resposible script reported it would create (this is not very important for my problem, just some background).
The problem is that when I run the algoithm more than one time the GameObject.FindGameObjectsWithTag() returns all the rooms that was ever created. Even the ones that has been destroyed and are no longer in the scene.
Here are the most important parts of my code:
void Start ()
{
while (nrOfRepeats < repeats)
{
clearLevel();
nrOfRepeats++;
createLevel();
}
checkConnectivity();
}
void clearLevel ()
{
GameObject[] rooms = GameObject.FindGameObjectsWithTag("Room");
foreach (GameObject g in rooms)
Destroy(g);
}
void checkConnectivity ()
{
GameObject[] roomsInScene = GameObject.FindGameObjectsWithTag("Room");
Debug.Log(roomsInScene.Count());
}
Say I would run the while lopp three times and the algorithm would create 10 rooms, 15 rooms and finally 10 rooms. I would only see 10 rooms in the scene, but the output in the console would still be 35. Anyone has any ideas what the problem here is?
Answer by SimplyEvert · Mar 18, 2014 at 12:55 PM
I found the problem. Apparently when you call Destroy(GameObject), Unity waits one Update frame before it removes the GameObject. Since all my code is executing in Start Update is never called, hence the rooms are never destroyed.
Answer by koray1396 · Mar 18, 2014 at 11:46 AM
It seems you have missing {} in your foreach loop and it's not destroying g.
If you only have one line after a statement like foreach, the {} arn't neccesary.
SimplyEvert is correct. In c# {} are not necessary if it is only the one line like above.