How to do 2D collsision detection most efficiently?

Hello Unity Community,

What’s the most efficient way to handle collision detection in a way that a sprite does not fall through an other collider while still triggering the OnTriggerEnter2D(), OnTriggerStay2D() and OnTriggerExit2D() methods?

For example: Immagine a scene with two objects:

  1. A 3D Cube object with a Box Collider 2D assigned to it, which serves as the ground.
  2. A 2D Sprite with a Rigidbody 2D and a Box Collider 2D assigned to it, positioned above the ground cube.

Pressing play let’s the sprite fall down until it hits the ground, which is fine so far. Now, to be able to switch between animations, the sprite should have its OnTriggerEnter2D(), OnTriggerStay2D() and OnTriggerExit2D() methods called. After enabling the sprites Box Collider 2DIs Trigger setting, the OnTrigger...() methods are called, but the sprite then falls through the ground. Now I wonder what’s the most efficient way to fix it. As far as I can tell, there are two obvious solutions:

  1. Using two Box Collider 2D components on the Sprite. One that prevents the sprite from falling through the ground by setting it’s Is Trigger flag to false. And a second, overlapping Box Collider 2D with it’s Is Trigger property set to true in order to get the callbacks invoked.
  2. Sticking with a single Box Collider 2D which acts as a trigger and then overwriting the sprites y velocity/position in every frame to prevent it from falling through the ground.

Both solutions should work. The question is, which of the two approaches is the better one in terms of efficiency? I assume that the second approach is more expensive - in terms of operations, but I honestly don’t know and it would be great if you could shed some light in this. Btw. if there’s a better solution, please let me know.

Thank you in advance!
M.

Why not use one collider, with IsTrigger set to false, and use OnCollisionXXX instead of OnTriggerXXX?