Crash Test Dummies — Using OnCollisions the right way in Unity

Don’t Panic!

Objective: Expanding on previously enabling Unity’s Physics engine through the use of a Rigidbody.

We want objects to be destroyed when they collide with each other as well as when they are hit with our laser object.

Implementation: There are two types of collisions in Unity using the right one in the right situation is key.

Hard or Surface Collision: This is used when you want a force reaction to occur on your object.

Pass-Through Collisions: Pass through collisions are use when you want the collision to be detected but you want to be able to get a message about that collision and perform some other action such as, collect coin give points or get his by laser, destroy object, give points, play sound, display explosion animation.

Every object we’ve created has a Collider and in order to enable collisions we need to add a Rigidbody to those objects. By default a Rigidbody has “Use Gravity” set to “On”, since our game is set in space and we have already created the movement scheme for our Objects we want to turn this off. Otherwise everything will be pulled down.

No back to the Object’s Collider. By default the Colliders are set to be hard surface colliders for our game we want them to be pass-through colliders so that we can use the OnCollider options and in order to this we need to enable “Is Trigger”. With this enabled the objects will pass through each other until we program them to do what we want when that happens.

I’ve enabled Is trigger on my Player, my enemy and my laser. I have also turned off gravity for all objects. Now I want to test and see if I get get on Trigger to detect my pass-through collisions. In my enemy script I will use OnTriggerEnter method and print a message to the console to confirm that everything is triggering the correct event.

The parameter that we are using is Collider other. The message we are sending to the console is saying: when something triggers the enemy’s collider “other” gets the object, transform the root of the object and name gives us its proper name.

Collisions detected!

Now that we’ve confirmed that our objects are colliding with no force reactions we can add some behavior based on what we want to do when these collisions happen. We’ll start off simple and build from there.

For the sake of this article we are going to trigger these events based on Object tags. Tags are a great way to group and then interact with similar type of Objects. You can create as many tags as you need and make sure to override them to your prefabs.

Tag…you’re it!

Now we’re going to flesh out the pseudo code from above using these tags We don’t need the Debug statement from before so we can get rid of that.

I’m going to use the CompageTag parameter as Unity told me it would be more efficient than (other.Tag == “Player”).

All the correct triggers!

Unity Developer — Technology Leader — Making Unity Game Development Look Easy