Skip to content

[Unity] How to Process Trigger and Collision Event

Last Updated on 2021-10-29 by Clay

In the process of making games with Unity, we usually need to deal with some collisions of game objects. For example: Get items, Hit the wall… and so on in different situations. At this time, we can OnCollisionEnter() and OnTriggerEnter() to handle collisions and trigger events.

The following record how to write collisions and trigger program, and the different Body Type situations.


Collision and Trigger

I am developing 2D game, so take the 2D game as an example.

Collision:

private void OnCollisionEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Snake")
    {
        Destroy(gameObject);
    }
}



Trigger:

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Snake")
    {
        Destroy(gameObject);
    }
}




Demo:


Different Physical Collision Trigger Table

collision detection occurs and messages are sent upon collision

Static ColliderRigidbody ColliderKinematic Rigidbody ColliderStatic Trigger ColliderRigidbody Trigger ColliderKinematic Rigidbody Trigger Collider
Static ColliderY
Rigidbody ColliderYYY
Kinematic Rigidbody ColliderY
Static Trigger Collider
Rigidbody Trigger Collider
Kinematic Rigidbody Trigger Collider
Reference from Unity official manual



Trigger message are sent upon collision

Static ColliderRigidbody ColliderKinematic Rigidbody ColliderStatic Trigger ColliderRigidbody Trigger ColliderKinematic Rigidbody Trigger Collider
Static ColliderYY
Rigidbody ColliderYYY
Kinematic Rigidbody ColliderYYY
Static Trigger ColliderYYYY
Rigidbody Trigger ColliderYYYYYY
Kinematic Rigidbody Trigger ColliderYYYYYY
Reference from Unity official manual

References


Read More

Tags:

Leave a Reply