When Game Objects Interact
At some point in your game, you’ll need your objects to interact. Whether it’s two cars crashing into each other or a projectile hitting an enemy or anything else you can think of, Unity provides two type of collisions to meet your needs: Surface Collisions and Trigger Collisions.
Surface collisions simulate how different types of objects that come into contact would interact with each other. Using the Unity Physics engine, you can create objects with different masses, materials and other properties and apply forces to them, such as gravity and acceleration.
For surface collisions to take place, both objects must have a Rigidbody component, which allows you to apply the Physics engine to your objects. In the example above, you can see several spheres colliding with each other and the movement of any one sphere is affected by the spheres it collides with.
In contrast, Trigger Collisions allow objects that come into contact to actually pass through each other. By avoiding this surface interaction, you have complete control over what happens as a result of the collision.
For a Trigger Collision to occur, a GameObject that has both a Rigidbody component and a Collider component with “Is Trigger?” set to True must collide with another GameObject that has a Collider component with “Is Trigger?” set to False. In the example above, the red Enemy object collides with the Player and turns white, but the movement of Player and Enemy are not affected by one another.
To get the most of the collisions in your game, you’ll want to be able to react to the collisions that occur. Unity provides a set of methods for each type of collision that allow you execute a block of code when a collision event occurs.
Surface Collision Methods
There are three methods for applying logic to a surface collision event:
- OnCollisionEnter: Called once when the surface collision starts
- OnCollisionStay: Called each frame while the surface collision is occurring
- OnCollisionExit: Called once when the surface collision ends
Surface collision methods also give you access to a collection of information about the collision itself, including the name of the other object or at point the collision occur. Depending on what kind of logic or functionality you want to add, you can use any of the above in a script attached to either object involved the collision.
Trigger Collision Methods
Much like surface collisions, there are also three methods for trigger collisions:
- OnTriggerEnter: Called once when the trigger collision starts
- OnTriggerStay: Called each frame while the trigger collision is occurring
- OnTriggerExit: Called one when the trigger collision ends
Unlike surface collision methods, trigger collision methods give you access to the other game object that collided with the object in focus.
No matter what type of interactions you need to build into your game, Unity’s collisions has you covered.