Unity3D: OnCollisionEnter Vs. OnTriggerEnter — Behaviors of Game Objects

This article covers the two types of colliders that can be scripted within game objects.

In the previous article, colliders and rigidbodies were discussed. With the trigger enabled within the collider, different actions and behaviors can be applied to game objects when collisions occur.

OnCollisionEnter involves the behavior of a collider rigid body when it collides with another at a point between their meshes. It is used primarily to determine the physical movement and property traits when colliding. It would be more suited for a scenario where two rubber balls hit each other and one needs to determine where they go.

OnTriggerEnter involves the behavior of a game object when it collides with another game object. It is used to determine what events get triggered when a game object (with a trigger enabled) contacts another game object (with its trigger enabled as well). It would be more suited for a scenario where a missile hits an enemy object and the enemy object must be disappear.

OnTriggerEnter can be used to destroy objects, enable powerups, and heal a player. Before diving into how to use OnTriggerEnter in our script, it is important to give our game objects tags.

Tags are simply assigned names assigned to your game objects. Going back to our Space Shooter 2D project, we would want to assign the tag “Player” to our Player game object.

For the laser, its tag will be laser.

In addition, the collider for each of these game objects should have the trigger enabled.

For our program, we need to determine what happens to our Player, Laser, and Enemy game objects. We will write our trigger scripts within our Enemy script since this game object will collide with both the Player and Laser while the these two will not collide with each other.

Within the Enemy script, we will callout OnTriggerEnter for when the Enemy collides an other game object. We want to write a script that does the following:

If gameobject collides with Player, destroy gameobject.

Here is how it will be written.

When entered into our Enemy sub class, the enemy game object will disappear when it collides with the Player.

In addition, we can do the same when the collides with the laser. However, the enemy game object and the laser will be destroyed.

Note there is a trend in this section of script. We can refer to game objects being triggered in relationship to the game object to which this script is assigned.

The next tutorial will go over how to use GetComponent for collision triggers.

Apprentice at GamedevHQ.