How to Get Mesh Class from GetObject Class in RhinoCommons?

            Mesh mesh0;
            using (GetObject getMeshAction = new GetObject())
            {
                getMeshAction.SetCommandPrompt("Please select a mesh");
                getMeshAction.Get();
                getMeshAction.EnablePreSelect(true, true);

                ObjRef meshref = getMeshAction.Object(0);
                RhinoObject meshobj = meshref.Object();
                mesh0 = meshobj.Geometry;
                if (!(meshobj.Geometry is Mesh)) RhinoApp.WriteLine("No mesh has been selected");
                
            }
            return Result.Success;

I am trying to get a Mesh from Rhino and have it run the Mesh.ClosestPoint(Point3d) Method.

But on this line:
mesh0 = meshobj.Geometry;

I cannot turn RhinoObject Class into Mesh Class.

Will be super grateful if you guys can show me how to do that?

You should set the GeometryFilter to a Mesh. This should be done before calling Get() along with enabling preselect.

https://developer.rhino3d.com/api/RhinoCommon/html/P_Rhino_Input_Custom_GetObject_GeometryFilter.htm

https://developer.rhino3d.com/api/RhinoCommon/html/T_Rhino_DocObjects_ObjectType.htm

Then you can do the casting with the is keyword like so

if(meshobj.Geometry is Mesh mesh)
{
    mesh.ClosestPoint(Point3d);
}

With this line:

mesh0 = meshobj.Geometry;

You need to cast the Geometry to a Mesh like so

mesh0 = meshobj.Geometry as Mesh;
2 Likes

Alternatively, without the need to cast, you can get a Mesh directly from the ObjRef.

https://developer.rhino3d.com/api/RhinoCommon/html/M_Rhino_DocObjects_ObjRef_Mesh.htm