static bool RaycastWorld(Vector2 position, out RaycastHit hit)
{
hit = new RaycastHit();
GameObject picked = HandleUtility.PickGameObject(position, false);
if (!picked)
{
return(false);
}
Ray mouseRay = HandleUtility.GUIPointToWorldRay(position);
// Loop through all meshes and find the RaycastHit closest to the ray origin.
MeshFilter[] meshFil = picked.GetComponentsInChildren <MeshFilter>();
float minT = Mathf.Infinity;
foreach (MeshFilter mf in meshFil)
{
Mesh mesh = mf.sharedMesh;
if (!mesh || !mesh.canAccess)
{
continue;
}
RaycastHit localHit;
if (HandleUtility.IntersectRayMesh(mouseRay, mesh, mf.transform.localToWorldMatrix, out localHit))
{
if (localHit.distance < minT)
{
hit = localHit;
minT = hit.distance;
}
}
}
if (minT == Mathf.Infinity)
{
// If we didn't find any surface based on meshes, try with colliders.
Collider[] colliders = picked.GetComponentsInChildren <Collider>();
foreach (Collider col in colliders)
{
RaycastHit localHit;
if (col.Raycast(mouseRay, out localHit, Mathf.Infinity))
{
if (localHit.distance < minT)
{
hit = localHit;
minT = hit.distance;
}
}
}
}
if (minT == Mathf.Infinity)
{
// If we didn't hit any mesh or collider surface, then use the transform position projected onto the ray.
hit.point = Vector3.Project(picked.transform.position - mouseRay.origin, mouseRay.direction) + mouseRay.origin;
}
return(true);
}