RaycastHit2D hit the wrong sprite

I have a number of sprites piled on top of each other. I am using RaycastHit2D to select the sprites, which all have BoxCollider2D, same z-position etc.

I also add sortingOrders to the sprites so they always is on top when selected.

Most of the time it works perfect but some times a sprite which is not on top is selected and not the one on top, which should have been selected. I have been trying to figure out what the problem can be but to no avail.

Here is the code line i think is related to the problem:

RaycastHit2D hit = Physics2D.Raycast( Camera.main.ScreenToWorldPoint( Input.mousePosition ), Vector2.zero )

Would appreciate a few tips on how to solve this annoying problem.

:face_with_spiral_eyes:

anyone?

Use Unity - Scripting API: Physics2D.OverlapCircleNonAlloc instead. You can then gather data on the selected within the ref array, and query as much rich data about what fell under the hit as you like. Possibly via dictionary lookup or other scheme.