I am trying to get my trigger to destroy all objects?

Hi, I am trying to get my trigger to destroy all objects under the same tag simultaneously. I can get it to work using a Getkey like this:

void Update ()
{
if(Input.GetKey(KeyCode.Space))
{
Destroy (GameObject.FindWithTag(“Red”));
}
}
}

but when I try to use On trigger enter it only destroys one at a time.

This is what my script looks like:

void OnTriggerEnter (Collider other)
{
Destroy (GameObject.FindWithTag(“Red”));
}

 }

I am very knew to scripting. any help will be appreciated.

Thanks

What do you mean one at a time ? Is it slower thatn with the first code example ? Or is it only when you enter into each collider ?

With the first example as soon as I press a key all game objects tagged Red are destroyed. With the trigger it will destroy one until I collide with the trigger again and then it will kill another. I want it to destroy everything at the same time.

1 Answer

1

GameObject.FindWithTag returns only one object (the first it finds with the right tag). But the first code example works for you because the Update method is called at every frame.

You have two possibilities, use FindGameObjectsWithTag, or call OnTriggerStay instead of OnTriggerEnter

Cool Thanks. I used OnTriggerStay instead of OnTriggerEnter it works perfectly now. The FindGameObjectsWithTag kept giving me errors.

I would suggest use OnTriggerEnter, else it more an hack then good pratice. Also, having a separate function would be better if you want to reuse the functionality in another context. void OnTriggerEnter (Collider other) { DestroyAllObject("Red"); } void DestroyAllObject(string tag) { GameObject[] ObjectsToDestroy = GameObject.FindGameObjectsWithTag(tag); foreach(GameObject DestroyObject in ObjectsToDestroy) { Destroy(DestroyObject); } }

@KiraSensei I would suggest you to use the Community Edit feature. I don't really like to post an new answer just to add more info and making it a more complete anwser. I feel it's like stealing. So this time, I've just add my stuf in the comment. Thank You

Thanks for all the help. I did have a problem with the player having to stay on the trigger before all the elements could be destroyed. Your new script works much better using on trigger enter instead of on trigger stay.