How to determine what GameObjects are below a mouse point (2D)?

I am trying to determine what game objects are at a given mouse point.

**Update: It fails if I have UI Scale Mode = Scale with Screen Size. Not sure why yet though. **

This way, on drag drop, when my OnEndDrag() event is fired, I can see what game objects are at the mouse point when drag ended. This will allow me to determine if any valid containers are below the mouse point so I can add the object being dragged to it.

I attached Box Collider 2D to my game objects. However, the RayCast always returns no hits at any mouse point.

What must be done to get a hit?

Here are the exact steps I took to test this:

  1. Create a new scene (2D)
  2. Add a Canvas
  3. Add Box Collider 2D to the canvas and make it as large as the canvas.
  4. Add a script to the scene and in Update() function show detect what objects are below the mouse point when mouse down is fired.

The following are various techniques to try to get a hit. All fail.

 void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("Mouse down");
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit2D raycastHit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10)), Vector2.zero);
            if (raycastHit)
            {
                Debug.Log("Hit: " + raycastHit.transform.gameObject.name);
            }

            Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero);
            if (hit.collider != null)
            {
                Debug.Log(hit.collider.name);
            }

            RaycastHit2D[] hits = Physics2D.GetRayIntersectionAll(ray, Mathf.Infinity);
            Vector2 v = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            Collider2D[] c = Physics2D.OverlapPointAll(v);
            if (c.Length > 0)
            {
                Debug.Log("Hit!!!");
            }

            RaycastHit2D[] allHits = Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
            if (allHits.Length > 0)
            {
                Debug.Log("Hit!!!");
            }
        }
    }

Throw a Graphic Raycaster component on the canvas and remove all those box colliders. Anything clickable you can add a button script to, then put your logic in the button’s On Click() event. I’m not sure about this but I’m pretty sure that BoxCollider 2D will ignore any collision in the z direction, because it is made for objects that are colliding on the X/Y plane.

Figured it out.

If you have your 2D canvas UI Scale Mode set to “Scale with Screen Size”.

Then use -Vector2.up for the direction:

RaycastHit2D[] allHits = Physics2D.RaycastAll(Input.mousePosition, -Vector2.up);