Unity2DでRaycastを使って座標からGameObjectを取得する

Raycastの練習として、やってみました。
ほかの取り方もあるかもしれません。

Vector3 pos = new Vector3(/* 好きな値 */);
RaycastHit2D hit = Physics2D.Raycast(pos, new Vector3(0, 0, 1), 100);

// 可視化
Debug.DrawRay(pos, new Vector3(0, 0, 100), Color.blue, 1);

// コンソールにhitしたGameObjectを出力
Debug.Log(hit.collider);

このhit.colliderでGameObjectを取れます。

マウス座標からもとれるよ

このやり方だと、遠回りになるかもしれませんが、
マウス座標からとるのも簡単です!
上のコードの最初の行を、次のように変えるとできます。

Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);