Sprite with higher sorting layer not firing its OnMouseDown function

I have 2 objects, both have a Box collider 2D.

The first object is on the Level1 Sorting Layer and has a Tile script attached to it.

The second object is on the Level0 Sorting Layer and doesn’t have any scripts.

1

The Tile script code is as follows:

void OnMouseDown()
{
    Debug.Log(Input.mousePosition.ToString());
}

Whenever I click the top tile, nothing prints in the console unless I click on the red area like I show in the image below (red area = [first box collider] minus [the two box colliders intersection area]).

enter image description here

Why this happens ? Why doesn’t the OnMouseDown() function fire up simply when you click on its collider, since the top tile is on a higher sorting layer than the bottom tile. How does this work ? Doesn’t sorting layer affect the 2D box collider ? (If I change the Z-axis of the top tile to -1, while keeping the bottom tile to 0, it works as expected.)

Unfortunately, OnMouseDown does not take into account the sorting layer. It actually casts a raycast, and calls the OnMouseDown of the first collider hit. Raycast is a physics function so it finds the one closest to the camera in world space, which means the one with lowest Z.

You can create your own input manager, that will use GetRayIntersectionAll to get all 2D colliders in mouse position, then sort them by sortingLayer/sortingOrder, and choose the first one.

RaycastHit2D[] hits = Physics2D.GetRayIntersectionAll(mainCamera.ScreenPointToRay(Input.mousePosition));