Home > Enterprise >  How do I check the tag of a GameObject when I collide with it?
How do I check the tag of a GameObject when I collide with it?

Time:10-08

My code is:

    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.CompareTag ("bullet"))
        {
            UI.lives--;
        }
        if (collision.gameObject.tag == "life")
        {
            UI.livePart  ;
        }
    }

I've tried two different methods of making it work and neither actually function correctly. For the top one, when my player object first collides with a gameObject with the tag "bullet", it should decrease my "lives" integer by 1.

For the second one, it should increase another integer "livePart" by 1 when it first collides with a gameObject with the tag "life".

UI is the code that is storing the variables "lives" and "livePart".

CodePudding user response:

One thing to check for is that the documentation mentions

Notes: Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached.

If you happen to have "Is Kinematic" checked in the inspector under RigidBody, then you will not get collision events.

Also, just in case this is new information, attaching a debugger to your scripts as shown here can really help. For example you can set a break point in the OnCollisionEnter funtion to verify that it is ever getting called.

  • Related