Problems with loops

Ok, this is likely to be a pretty difficult one for you to help me with, but, anyway…
I’m making a game. At one point, you fly into a portal, stuff happens. One of them things is it should destroy all objects with tag ‘obstacle’. This works perfectly the first time. The second time, however, it doesn’t. Here’s the code:

        rocks = GameObject.FindGameObjectsWithTag("obstacle");

        for (var i = 0; i < rocks.Length; i++)
        {
            Destroy(rocks*);*

}
I know the function that that’s contained in is run both times, but… like I said, the obstacles stay the second time round.
Weirdly, two other loops are run when the player flies into the portal in another script and neither of them work the second time either. Here’s one:
foreach (Transform child in transform)
{
GameObject.Destroy(child.gameObject);
}
and here’s the other:
foreach (GameObject i in Planets)
{
i.transform.parent = transform;
}
So, I know the problem seems pretty vague, but I’d appreciate any ideas. I’m completely clueless as to why they’d only work once.
Thanks.
EDIT:
Just to include what I said below, changing that second code snippet to
foreach (GameObject i in Planets)* *{* *Destroy(i);* *}
fixes it.
Still stuck with the other two though…

Depending on how quick you fire this event the second time, it may be that Unity is being slow on garbage collection. I noticed recently that calling Destroy() doesn’t guarantee that the object will be destroyed right then.

So what you can do is to first make it that when a rock is created it is also added to a static list of rocks. Then when you do your foreach, you both destroy the objects on that list AND remove them from the list (important!). Then when it checks the list the second time they at least won’t be on the list, even if they are still sort of existing somewhere waiting to be destroyed. I hope that helps!

I fixed this. The problem was to do with not removing planets from their list properly after destruction. Changing that made everything else work :slight_smile: