Collisions vs Triggers using Unity physics

Collisions and Triggers

Following on from my last article, we’re going to look at the differences between collisions and triggers and making use of the Unity physics system.

The decision as to whether you want a collision or a trigger is down to the intended purpose of the collider. If you want a physical collision to occur between two GameObjects, then both must be set as non-triggers.

To Trigger or not to Trigger

If you don’t want the physical collision but just want to be able to run some code based on one object entering the proximity of another, at least one of the colliders must be set as a trigger.

From a Unity design perspective, that really is the only difference. From a coding perspective, we actually have as many similarities as we have differences. Both Collisions and Triggers activate messages depending on the current state of the collision —

Enter — sent on the frame 2 colliders contact.

Stay — sent on frames the 2 colliders are in contact (exact frequency differs between Collision and Trigger types).

Exit — sent on the frame the 2 colliders part contact.

We can run code when these messages are sent by calling their respective methods in scripts attached to the same GameObject as the collider.

It is important to note that just as colliders and rigidbodies have 2D and 3D variants, so do the messages sent from the colliders. For example —

2D and 3D versions of trigger Enter methods

The Collider argument passed into each of these methods refers to the ‘other’ collider that caused this code to run. From that we can gain access to information on that collider and the GameObject it’s attached to.

Examples of Collision type methods

Trigger messages are only sent (and therefore only calling the equivalent methods) if the collider is set as a Trigger and conversely, Collision messages and methods only apply with colliders that are not set as Triggers.

The 3D variants available — for the 2D variants, simply add ‘2D’ to the end of the method name

With these different capabilities with each type of collider, we have a huge flexibility when it comes to implementing different functionality to suit each stage of any collision we encounter and want to do something with.

I think we’re about ready to get some enemies into our game, that’ll be my next article…

A UK based Unity Developer with a passion for gaming and coding