0
\$\begingroup\$

I've made a hole. I have animals tagged as animals. When an animal walks into the hole, they disappear. I tried OnTriggerEnter2D() as well, and set the collider to isTrigger, but it still didn't work. I can get it to work without the tag part, but anything that bumps into each other sets each other to inactive.

public class BlackHole : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "animal")
        {
            other.gameObject.SetActive(false);
        }
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ Does your animal object have children objects with colliders? If so you need to make sure their tag is also set to "animal". \$\endgroup\$ Commented Feb 13, 2017 at 2:31
  • \$\begingroup\$ @Infodayne, this sounded incorrect, so I tested it. Child game object tags do not conflict with the direct game object, when you check its tag. \$\endgroup\$
    – Gnemlock
    Commented Feb 13, 2017 at 3:11
  • \$\begingroup\$ @Gnemlock Yes, but perhaps his root animal gameobject is simply a container/parent. If this root gameobject has the correct tag, but no collider, then the tag of the children nodes need to be set to "animal". \$\endgroup\$ Commented Feb 13, 2017 at 3:27

1 Answer 1

1
\$\begingroup\$

The fact that this works, but only if you omit the tag statement, implies that the only possible cause derives from your tagging. You must ensure that the required game objects have the exact same tag; in this case, animal. Tags are case sensitive, so a game object tagged as "Animal" will not return true if you check for a tag of "animal".

The game object must list the required tag as it's "tag", under it's name.

As a final note, when we create custom tags, they do not automatically apply to a game object - even if we have been directed to the custom tags screen through the tag selection for that game object. It is fairly easy to forget this, but we must actually set the tag to the game object, after creating it.

\$\endgroup\$
1
  • \$\begingroup\$ Don't forget to note that CompareTag("foo") is generally to be preferred over .tag == "foo". One requires pulling a string from unmanaged code into managed code (allocations) and the other doesn't. ;) (See this thread for details) \$\endgroup\$
    – DMGregory
    Commented Feb 13, 2017 at 4:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .