Colliders vs Triggers - when to use what?
Colliders and Triggers are commonly used techniques in games to detect when objects collide.Ā
Let's start with the basics.Ā
~ Say you have a plane with Mesh collider as the floor.
~ Add a bullet object with a rigidbody and gravity attached to it.Ā
This object would fall through the floor since it has no colliders.Ā
Let's apply a box collider to it.Ā
Now when it falls on the floor, it would not fall through the floor because the collider is preventing it from passing through the floor which also has a mesh collider.
Ā At this time, the collision events are called.
~ e.g. OnCollisionEnter ==> gets called
Attach this script to the bullet object:
#pragmaĀ strict functionĀ OnCollisionEnterĀ (colĀ :Ā Collision) { Ā Ā Ā Ā Ā Ā Ā Ā Debug.Log("Entered collisionĀ zone"); }
Notice how the behavior for the bullet has changed because it has a collider around it.Ā
This type of collider serves two main purposes for the bullet:
1) It prevents the bullet from passing through the floor
2) It gives us the ability to add custom code when such collisions occur
If you care about both of these behaviors then Collisions is the right framework to use.
In case, all you want is the ability to write custom code when such collisions occur, then you might consider triggers for your behavior.
You can convert the box collider into a trigger by checking theĀ
~ Trigger Enabled = YES
If you check the trigger box the bullet will fall through again, even though the bullet has a box collider around it.
At this time, the trigger events are called.
~ e.g. OnTriggerEnter ==> gets called
Attach this script to the bullet object:
#pragmaĀ strict functionĀ OnTriggerEnterĀ (colĀ :Ā Collision) { Ā Ā Ā Ā Ā Ā Ā Ā Debug.Log("EnteredĀ trigger zone"); }
Notice that we no longer receive the collision messages and only receive the trigger messages.
TRIGGERS
If all you want is to write custom code when two game objects collide then Trigger is a cheap optimal way to achieve just that.
Triggers are best suited for:
~ Attack (punch, kick, sword, etc)
~ Bullets behavior
Trigger events are only sent if :
> Both objects have colliders attached
> One object has a rigid body attached
> One object has marked "Is Trigger" = "YES"
COLLISIONS
If you want to prevent two objects from colliding and you want to write custom code when they touch each other, then Collision is the way to go.
Ā Collisions are best suited for:
~ Cars bumping into each other
~ Items falling from top to floor
Collision events are only sent if:
> Both objects have colliders attached
> One object has a rigid body attached
> All objects have "Is Trigger" = "No"
Hereās a sample app (using Unity 5):
https://github.com/anilo/testColliders









