Unity2D游戏,为什么我的游戏对象没有被破坏

Unity2D games , why my gameObject not destroyed

为什么我的名为“pipo”的游戏对象没有被销毁 这是我的脚本:

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.name == "pipo")
    {
        Destroy(other.gameObject.transform.parent.gameObject);
    }
}

尝试稍微更改您的代码,首先您通常应该使用 CompareTag(),它会在给定标签不存在时给出错误消息。

之后,您可以添加检查以查看游戏对象是否有父级,并根据该检查销毁其父级或自身。

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("pipo")){
    return;
    }

    if(other.gameObject.transform.parent) {
        Destroy (other.gameObject.transform.parent.gameObject);
    }
 
    else {
        Destroy ( other.gameObject);
    }
}

当对象仍然没有被销毁时,您需要确保:

  1. 您要销毁的游戏对象具有名为“pipo”的标签
  2. 此脚本所在的 GameObject 启用了 IsTrigger 以及 Collider
  3. “pip”GameObject 有一个 Colllider,但未设置为 IsTrigger
  4. 两个对象都附加了一个 Rigidbody 组件
  5. Collider 附加到“pipo”GameObject 而不是其父项