Unity 2D Raycast from mouse to screen

See this thread:

http://forum.unity3d.com/threads/210960-Raycast-with-sprites

But basically, if you just want to click the mouse directly on an object and have the raycast hit it, this should work:

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

if(hit.collider != null)
{
    Debug.Log ("Target Position: " + hit.collider.gameObject.transform.position);
}

The Raycast point needs to be in world coordinates, and setting a distance vector of zero means that it will only intersect with the object immediately under the cursor.

26 Likes