Eggys Games

Unity - Basic Collisions in C#

Posted on by Eggy

In Unity the first thing you're gonna want to be using is collisions. This is what happens when 2 objects collide with each other, or rather two rigidbodies with colliders. Below is all you will need to get started. By adding a rigidbody and a box collider our object can now hit other objects in the scene.

Below I've included the functions that Unity uses to test for collision between objects. Simple copy and paste and then write inside the code you want to execute when these objects collide.

You will see their is triggers and normal. The difference with trigger is that the object will not collide with it in physics space, however it will still execute a hit-test. You use triggers on objects in the background like levers, scenery, doors etc. Where as normal collisions are for enemies and the player. 

These are the two components you need on an object to run a hit-test

Use This code below when you want a hit test between two objects

 //Basic Collision 
 void OnCollisionEnter2D (Collision2D col) {
    if (col.gameObject.tag == "NameOfObject") {
         ///Run Code 
     }
 }

 //Collision Exits
 void OnCollisionExit2D (Collision2D col) {
    if (col.gameObject.tag == "NameOfObject") {
         ///Run Code 
     }
 }

 //Non-Physics Collision
 void OnTriggerEnter2D (Collider2D col) {
 }

 //Non-Physics Collision Exit
 void OnTriggerExit2D (Collider2D col) {
 }