Search code examples
pythonselectmayamel

Maya Python : Im listing relatives of a group but when i go to select the relatives it says none


Hi so Im trying to list all the relatives of this group in Maya. it returns the list fine, but when i go to select everything in the list, it prints out that none is selected?

mySel = cmds.ls(selection=True)
print(mySel)

rel = cmds.listRelatives(ad=True , pa=True)
print(mySel)

cmds.rename(mySel + '_grp')

Solution

  • Welcome to SO!

    Right now when you use cmds.ls(selection=True) to capture the selection it will return you a list of strings.

    The rename method expects 2 strings as parameters, an existing object to rename, and what to rename it to.

    So what you're doing now is passing mySel, a whole list of strings, when it only accepts one. If you want to rename multiple objects at once then you need to use a for loop to operate on them one by one:

    import maya.cmds as cmds
    
    mySel = cmds.ls(selection=True) # Get a list of the current selection.
    
    for i, obj in enumerate(mySel): # Loop over selection, one by one.
        newName = "{}_{}_grp".format(obj, i) # Build the new name.
        cmds.rename(obj, newName) # Finally rename the object.
    

    Also with cmds.listRelatives it's possible that it will return None if the object has no shapes/children, or you simply have nothing selected. So you may need an if condition to make sure it returns something.

    Hope that makes it more clear.