OnCollisionEnter Vs. OnTriggerEnter — When to use them?
Day 11- Making 2D Space Shooter Game
Triggers are colliders that are capable of executing script when a collider touches the trigger, exits the trigger, or while the collider touches the trigger via OnTriggerEnter, OnTriggerExit, or OnTriggerStay. You also optionally have access to the collider that touched your trigger.
As you can see in the GIF above, when the enemy(red) touches our player(blue), a message is sent in our console as it passes through. It is because our gameobjects are set to Is Trigger and it detects when enemy passes through player and runs the above script.
A collision is also the result of an object touching another one, but instead of passing through, these objects push each other in a realistic way. You need to disable Is Trigger to access collision.
Now if you use OnColliderEnter instead of OnTriggerEnter, you will see that the enemy won’t trigger when it collided with player; it only knows it collided and reacts to it.
So when should we use either of these?
OnTriggerEnter() is used to detect collision but it does not act as solid body , rather allows the gameobjects to pass through them. you can use a trigger when you have an object which doesn’t interact physically. ex: checkpoints, power ups, etc.
OnCollisionEnter() is used to create Collisions between objects. Gameobjects collide with each other and get repelled by their forces. Ex: when two car collides, when using throwables, etc.