how do I get coordinates anywhere on a 3d object in c#, unity

610 Views Asked by At

So, I have a 3d object, and I am trying to get the x,y,z position when I click anywhere within the 3d object, but I have no idea how.

For example, if I were to click in the middle of the 3d object, it will give me coordinates (0,50,0). and if I click on the top left, it will say (0,0,0).

EDIT: I want to get the coordinate when I click anywhere on my 3d object relative to the object pivot point

1

There are 1 best solutions below

0
derHugo On

you can do the following (assuming your object has a MeshCollider attached - or any other Collider but of course you will get the point on the collider not the mesh itself)

var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out var hit))
{
    var worldPoint = hit.point;
    var relativePoint = hit.transform.InverseTransformPoint(worldPoint);

    Debug.Log($"You have hit object {hit.gameObject} at position {relativePoint.ToString("G9")}");
}

See