简体   繁体   English

如何一次销毁多个游戏对象?

[英]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"));
    }
}

Destroy(Object) takes in an Object, more specifically, a component or a game-object; Destroy(Object)接受一个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. 如果要销毁与之碰撞的游戏对象,则Destroy(collision.gameObject)会这样做。

If you want to destroy all GameObjects with a specific tag, you can do GameObject.FindGameObjectsWithTag(tag) , like so: 如果要销毁带有特定标签的所有GameObject,可以执行GameObject.FindGameObjectsWithTag(tag) ,如下所示:

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. 还有一些其他方法,例如Object.FindObjectsOfType(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. 您可以考虑先将相应的游戏对象缓存在某个位置,然后再销毁它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM