Search code examples
pythonmaya

Get Object Type into Group in Outliner Maya


I try to get all object type for each element into the group in Outliner.

This is my code.

from maya import cmds

objects = cmds.ls(selection=True, dag=True)

objects.sort(key=len, reverse=True)

# Now we loop through all the objects we have
for obj in objects:
    # We get the shortname again by splitting at the last |
    shortName = obj.split('|')[-1]

    children = cmds.listRelatives(obj, children=True) or []

    if len(children) > 0:
        for current in children:
            objType = cmds.objectType(current)
            print(objType)

I got this error:

Error: RuntimeError: file /Users/jhgonzalez/Library/Preferences/Autodesk/maya/2018/scripts/AssigMaterialForEachMesh.py line 26: No object matches name: SafetyHandle_019_allFromGun:pCylinderShape21 Object 'SafetyHandle_019_allFromGun:pCylinderShape21' not found.

And I'm testing this code with this

enter image description here


Solution

  • The problem is that you aren't using long names, so the script will crash if there are objects with duplicate names as Maya doesn't know how to resolve it.

    For example, let's say you have a hierarchy of 3 nodes:

    |a
      |b
        |c
    

    And another hierarchy with 2 nodes:

    |d
      |a
    

    Since you're using short names, when you try to query objectType from a, it doesn't know from what hierarchy you want it from, thus just use long names:

    from maya import cmds
    
    objects = cmds.ls(selection=True, dag=True, l=True) # Use long parameter.
    
    objects.sort(key=len, reverse=True)
    
    # Now we loop through all the objects we have
    for obj in objects:
        children = cmds.listRelatives(obj, f=True, children=True) or [] # Use full parameter.
    
        if len(children) > 0:
            for current in children:
                objType = cmds.objectType(current)
                print(objType)
    

    Now it continues to work as expected, despite having duplicate names in your scene.