Mike
Mike

Reputation: 180

How can I destroy multiple game objects at once?

I am trying to figure out how I can basically stand on a pressure plate and have something that's in the way disappear. I have it working to destroy the object you interact with but not finding any solution to make another object be destroyed.

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.CompareTag("PressurePlate"))
    {
      Destroy(collision.gameObject.CompareTag("tree"));
    }
}

Upvotes: 1

Views: 2987

Answers (1)

WQYeo
WQYeo

Reputation: 4071

Destroy(Object) takes in an Object, more specifically, a component or a game-object;
(Though nothing would happen if you attempt to destroy a boolean, like what you did in this case; Someone can correct me on that though.)

If you want to destroy the game-object that it has collided with, Destroy(collision.gameObject) would do it.

If you want to destroy all GameObjects with a specific tag, you can do GameObject.FindGameObjectsWithTag(tag), like so:

foreach (var gameObj in GameObject.FindGameObjectsWithTag("Your target tag")){
  Destroy(gameObj);
}

There are a few other methods like Object.FindObjectsOfType(Type) which you can use to fetch all game-objects with a certain type.

But since they are generally slow, I do not highly recommend using those unless you need to;
You can consider caching the respective game-objects somewhere first, and destroying them later.

Upvotes: 2

Related Questions