OnCollisionEnter vs. OnTriggerEnter — When to use them?
Today we will talk about collisions between game objects. There are 2 types of Collisions;
- A hard collision is when two objects collide and apply force to the objects. An example of this would be throwing a ball at a wall and the ball bouncing back. To set up an object for a hard collision you will need to make sure the is trigger attribute of the collider is uncheck
The method you would use is to check for the hard collision will be one of the following: OnCollisionEnter, OnCollisionStay, OnCollisionExit.
2. A trigger collision is when two objects collide and pass through each other. An example of this would be when your player is collecting coins. you pass through the object and collect it. To set up a trigger collision you will need to check the Is Trigger attribute of the collider component.
The method you would use is to check for the trigger collision will be one of the following: OnTriggerEnter, OnTriggerStay, OnTriggerExit.
I will show an example of a Space Shooter game, where I set up the collision with the Enemy from the Player and a Laser. When the enemy collides with the player or a laser, the enemy will be destroyed. First, we will set the collider as a trigger and add the rigid body. we will set is trigger on the Player, Enemy, and Laser. We will add the RigidBody to just the Enemy and Laser.
Now we will need to add the code to the enemy script. You will notice the method uses a variable name other. This variable will store information about the object that collided with the enemy. The code will determine which object collided and destroy the Enemy.
Here is the code in action
Happy Coding!