Suppose you want to get the node names below the selected hierarchy. I think the first thing that comes to mind is the listRelatives command. You can get the child hierarchy using the listRelatives command.
https://help.autodesk.com/view/MAYAUL/2020/JPN/index.html?contextId=COMMANDS-INDEX
cmds.listRelatives( ad=True, c=True, typ="transform" )
However, if you get it this way, it is difficult to use because the order in the list is not hierarchical.
#result: [u'_03', u'_02', u'_01', u'_05', u'_07', u'_06', u'_04'] #
The above is the result of executing the command by selecting "_00". If you reverse () the retrieved list, it will be in hierarchical order, but it is not smart.
Therefore, we will solve it using Open Maya.
import maya.OpenMaya as om
def getHierarchicalNameList():
list = []
selList = om.MSelectionList()
om.MGlobal.getActiveSelectionList(selList)
for i in range(selList.length()):
dag = om.MObject()
selList.getDependNode( i, dag )
dagIterator = om.MItDag( om.MItDag.kBreadthFirst, om.MFn.kInvalid )
dagIterator.reset( dag, om.MItDag.kBreadthFirst, om.MFn.kTransform )
fDn = om.MFnDagNode()
while ( not dagIterator.isDone()):
currentObj = dagIterator.currentItem()
fDn.setObject(currentObj)
fName = fDn.name()
list.append( fName )
dagIterator.next()
return list
We will use the Open Maya iterator. An iterator is a data set structure. Since the parent-child hierarchy is a set structure of DAG, MItDag class is used.
dagIterator = om.MItDag( om.MItDag.kDepthFirst, om.MFn.kInvalid )
Create an iterator. The arguments are [type] and [filter]. Tpye specifies the search type.
--kDepthFirst: After searching the child hierarchy, move to the sibling hierarchy. --kBreadthFirst: After searching the sibling hierarchy, move to the child hierarchy.
When you run each Tpye, there are the following differences.
# kDepthFirst
[u'_00', u'_01', u'_02', u'_03', u'_04', u'_05', u'_06', u'_07']
# kBreadthFirst
[u'_00', u'_01', u'_04', u'_02', u'_05', u'_06', u'_03', u'_07']
You can set the filter with filter. kTransform has the filter disabled. See here for other filters.
dagIterator.reset( dag, om.MItDag.kBreadthFirst, om.MFn.kTransform )
Resetting the iterator. Here you specify the DAG node you want to search. I want to get only the Transform, so I'm setting the filter in MFn.kTransform.
while ( not dagIterator.isDone()):
dagIterator.next()
Loop through the while until the iterator finishes. Use the next () method to move to the next node. Please note that if there is no next, it will be an endless loop.
In addition to MItDag, iterator classes include node networks (MItDependdenctGraph), vertices (MItVertex), and polygons (MItMeshPolygon). If you hold down the above points, you can handle them all in a similar way. It can be processed faster than cmds, so please take advantage of it.
Recommended Posts