Collisions between UI elements in Unity

Sunil Nair picture Sunil Nair · Apr 4, 2016 · Viewed 11.2k times · Source

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?

Answer

Sunil Nair picture Sunil Nair · Apr 4, 2016

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.