4

I am able to detect collision between UI components and a gameobject if my canvas is rendered in the world space. Here, I am trying to find collision between two UI elements (say UI buttons) when the canvas render mode is screen space overlay.

I added box collider components to my UI buttons and tried using OnCollisionEnter2D and OnTriggerEnter2D. But, the collision is not detected. Is there a way to detect the collision?

Sunil Nair
  • 383
  • 2
  • 5
  • 15

1 Answers1

8

The question does not require a code body. However, I have figured out a solution. TO both the UI elements, you need to:

  • Attach a rigidbody2d component
  • Attach a box collider component
  • disable gravity
  • enable the isTrigger checkbox.

Now in the script attached to one of the UI elements:

void OnTriggerEnter2D(Collider2D other) 
{
    Debug.Log ("Triggered");
}

This would detect the collision.

Nahuel Ianni
  • 3,177
  • 4
  • 23
  • 30
Sunil Nair
  • 383
  • 2
  • 5
  • 15
  • Turning off the gravity is just to prevent the UI elements from falling down? Or is it necessary for the actual collision detection? – LilaQ Apr 04 '16 at 20:30
  • It is only to prevent the UI elements from falling down. – Sunil Nair Apr 05 '16 at 06:02
  • 3
    Man, I was using OnCollisionEnter and OnCollisionEnter2D, thanks for highlight we need to use OnTriggerEnter2D, it was the detail I was missing. Instead of change the gravity to zero I just made it kinematic, no need to ask the rigidbody to do any other calculation. But your solution worked just fine, thank you. – Fernando Bonet Mar 27 '19 at 11:26