Doers of Stuff.org

A place to Do Stuff and see Stuff Done…

OnCollisionEnter vs. OnTriggerEnter – When to use them?

Unity’s OnCollsionEnter() and OnTriggerEnter() methods are part of the Collider class and are triggered when the two properly configured objects collide. In a simplified sense, OnCollisionEnter() is used when you want colliding objects to react as they would in the physical world. Think of objects bouncing or ricocheting of each other. Use OnTriggerEnter() when you want to define the resulting action yourself. Think of collecting tokens.

To invoke a non-physical action on collision such as a power-up or object destroy, the object triggering the action must have the following. It has to have a Collider component and a Rigidbody component. The Collider must have the “Is Trigger” field selected. Then the script attached to the game object must have an OnTriggerEnter() method defined.

    private void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            Destroy(this.gameObject);
        }
    }

When another game object with a collider component collides with this game object, the OnTriggerEnter() method is called. As you can see a Collider object is passed in. This Collider is a reference to the object that hit it.

Now, things can actually get a bit more complicated, so it is useful to read the Unity documentation for both of these methods. In fact, you’ll probably have to read them multiple times unless you are already familiar with their inner workings. For instance, the OnCollisionEnter() method says:

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

https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html

Therefore, if you have the object marked “Is Kinematic” in the Rigidbody component, the objects will pass through each other.

OnTriggerEnter() on the other hand has the following to say in its documentation.

If both GameObjects have Collider.isTrigger enabled, no collision happens.

https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html

Personally, I would not have expected this last one. However, I did some quick testing on this, and it doesn’t seem to be true. I enabled the “Is Trigger” flag on the Player Collider and the Enemy Collider but instead of passing through each other, the collision was triggered, and the Enemy game object was still destroyed.

Perhaps some more testing is in order…

Leave a Reply

OnCollisionEnter vs. OnTriggerEnter – When to use them?

by Robert time to read: 1 min
0