Project 1: Space Shooter

How to detect collisions in Unity

OnTriggerEnter vs OnCollisionEnter

Successful collision between the laser and the enemy.

So at the moment neither my lasers have any effect on my enemies, nor my enemies to me. How to solve this? After browsing through the Unity manual I found two options OnTriggerEnter and OnCollisionEnter that could solve my no effect problem.

So which one to use? Mostly it depends on what we want to achieve. The OnCollisionEnter is called when two objects start to collide, it provides a Collision class object for the method, which contains information regarding the collision. That is, it has information such as the points of collision, the velocity and the other object’s identity, among other things, but information is the only thing it has.

On the other hand the OnTriggerEnter is called when one object collides with another. It passes a Collider class object for the method, and through this the other object can be manipulated unlike the Collision class objects.

To put it differently, if I would use the OnCollisionEnter method in the Enemy object I would get information on all the collisions it has, but the only thing that I could affect after this information is the Enemy object itself. So for example I could use it to change the color of the Enemy object after it hits something, or I could use it to determine which side was hit and make it move to the opposite direction.

This means that I have to use the OnTriggerEnter as my choice to handle the collisions, since this will give me the option to not only manipulate the Enemy object, but also to manipulate the colliding object. The reason why I want to do something with the colliding object, is that I want to destroy both the laser that hits the enemy and the enemy itself.

One last thing to remember is that I have to be careful with the order I destroy these objects. If I were to destroy the Enemy object before I destroy the Laser object, the Enemy script would be destroyed before the rest of the code could be run, which could lead to the laser not being destroyed.

OnTriggerEnter inside the Enemy script, note the order in which the objects are destroyed.

While I tested this, if the Enemy script doesn’t have any time consuming tasks after being destroyed, it could still run the next command before the next game update happens. That means, in my case, that the laser was destroyed even though the Enemy object was destroyed before it. But this doesn’t mean that it would happen similarly in other situations, so I and everyone else have to remember to destroy the object whose script is being run as a last item.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store