OnCollisionEnter VS OnTriggerEnter (Game Dev Day 11)

Jack Leavey
2 min readJul 23, 2021

--

Collisions serve multiple purposes in video games. It is how projectiles connect to the player or enemies, powerups or collectables are “picked up”. Anytime two objects have to physically touch, we need to use a collision command.

The two collision commands we use in Unity are OnCollision and OnTrigger.

OnCollision is very simple; The program is checking to see if two Collider objects touched.

OnTrigger checks to see if EITHER object had a collider, and if it was set as a trigger object. We will be using OnTrigger for our Space Shooter example.

This command tells our Enemy object what to do if it collides with the Player object.

In English, this command is stating:

If the object I collided with has the tag “player” get the component “Player” from the object.

This lets the Enemy object access the script attached to the player object.

For this to work we need to place a Tag on our Player Object. Tags can be created inside the Unity program, and some are even premade by default (Like the Player tag).

Next:

Damage the player (Damage is a variable set inside the Player script)

A “Lives” System.

Finally:

Destroy this object (the enemy)

This was simple because we set the Player’s collider to be a trigger.

Is Trigger MUST be checked for a collision to work with OnTrigger.

We could have accomplished this with OnCollision, but in the effort to keep things simple and neat, it was better to use OnTrigger for this example.

--

--

Jack Leavey
Jack Leavey

Written by Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!

No responses yet