OnCollisionEnter VS OnTriggerEnter (Game Dev Day 11)
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.
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)
Finally:
Destroy this object (the enemy)
This was simple because we set the Player’s collider to be a trigger.
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.