Ananda
Ananda

Reputation: 47

Unity2D games , why my gameObject not destroyed

Why my GameObject named "pipo" is not destroyed This is my script:

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

Upvotes: 4

Views: 452

Answers (1)

IndieGameDev
IndieGameDev

Reputation: 2974

Try to change your Code a little bit, first you should generally use CompareTag() which gives Error Messages when the given Tag doesn't exist.

After that you can add a check to see if the gameobject has a parent and depending on that destroy its parent or itself.

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

When the object still doesn't get destroyed, you need to make sure that:

  1. The Gameobject you want to destroy has the tag called "pipo"
  2. The GameObject where this script lies has IsTrigger enabled as well as a Collider
  3. The "pip" GameObject has a Colllider and is not set to IsTrigger
  4. Both objects have a Rigidbody component attached to them
  5. Collider is attached to the "pipo" GameObject and not its parent

Upvotes: 5

Related Questions