How do we get an object’s shape node through the API?
If you can get the MDagPath of the object then you can get the shape node. MDagPath has a member function called extendToShapeDirectlyBelow. This function works on a dag path that ends in a kTransform node. In the example below I create a polySphere and get it’s MDagPath. This path ends in a kTransform so we can use extendToShapeDirectlyBelow() to grab the shape node. All we do is give it an index to the shape node we want. Since our poly sphere only has one shape the index will be zero (0). Doing this changes the original MDagPath to point at the sphere’s kMesh(shape) node instead of it’s kTransform node. At this point anything you do with the dag path will affect the shape node.
Next time I’ll cover object’s with multiple shape nodes and how to retrieve those shapes. This will make use of MScriptUtil.
import maya.cmds as cmds
import maya.OpenMaya as OpenMaya
# Create the sphere.
obj_name = 'Ball'
cmds.polySphere( name=obj_name )
# Get the MDagPath of the object.
sel_list = OpenMaya.MSelectionList()
sel_list.add( obj_name )
dag = OpenMaya.MDagPath()
component = OpenMaya.MObject()
sel_list.getDagPath( 0, dag, component )
# Show that we have the trasnform node.
# Extend the MDagPath to the shape node.
dag.extendToShapeDirectlyBelow( 0 )
# Show that we now have the shape node.