FindWithTag Doesn't work in loop?

So I’m trying to refresh the scene by deleting all the blocks I create (around 100). I don’t want assign them all to an array as this is just for debugging purposes.

I run a for loop after cloning these blocks to find a block with the same tag, in theory it should delete each block and move on to the next. It doesn’t work.

I am thinking that the command stays frozen to that object until it updates. Again, this is not for game play purposes, this is for debugging. Deactivating isn’t what I want to do.

Anyway, here is what I’m working with. Any ways around this tag issue? or fixes to what I might be doing wrong?

void Update () {
        if (blockCount < blockMax) 
            Instantiate(block, position, rotation);
        if (Input.GetKeyDown("space"))
        {
            for (int i = 0; i < blockCount; i++)
            {
                Destroy(GameObject.FindWithTag("block"));
            }
        }
}

I’m not sure what you mean by “stay frozen to that object”. What happens is, Destroy() does not take immediate effect, so that block still exists on the next loop iteration. FindWithTag() is not intended in situations where you care which object with a tag is returned. Instead, use FindGameObjectsWithTag() to get all of them.

Well, the problem is that Delete is delayed until the end of the current frame. I guess your FindWithTag returns always the same object.

Try to disable it in addition. FindWithTag can only find “active” gameobjects. Not sure if disabling affects the GO immediately but it could work.

Otherwise it would be better to use FindGameObjectsWithTag.

if (Input.GetKeyDown("space"))
{
    GameObject[] objs = GameObject.FindGameObjectsWithTag("block");
    foreach (GameObject O in objs)
    {
        Destroy(O);
    }
}