x


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"));
            }
        }
}
more ▼

asked May 31 '11 at 12:02 AM

SirGive gravatar image

SirGive
1.2k 25 32 50

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered May 31 '11 at 12:11 AM

sneftel gravatar image

sneftel
1.7k 7 9 20

Thanks. By "frozen to that object" I meant that I thought the tag might have stayed referenced until the current frame was over.

May 31 '11 at 12:15 AM SirGive
(comments are locked)
10|3000 characters needed characters left

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);
    }
}
more ▼

answered May 31 '11 at 12:17 AM

Bunny83 gravatar image

Bunny83
45k 11 48 206

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1668
x33

asked: May 31 '11 at 12:02 AM

Seen: 931 times

Last Updated: May 31 '11 at 12:17 AM