Search code examples
pythonmaya

Maya Python Delete children from a duplicated joint


I'm trying to delete the children from a joint that I duplicated in maya with python and is not working. What am I'm missing ?

import maya.cmds as mc
mc.duplicate('spine02_Joint',n='spineGrpJnt')
mc.parent('spineGrpJnt',w=True)
mc.select('spineGrpJnt')
childJnts = mc.listRelatives(ad=True)
mc.delete(childJnts)

From what I'm understanding this should delete everything in the childJnts but it gives me the error : ' More than one object matches name:'


Solution

  • You can drastically simplify your code by using the parentOnly kwarg in the duplicate command so that it duplicates the node you specify without any of its children

    import maya.cmds as mc
    
    new_jnt = mc.duplicate('spine02_Joint', n='spineGrpJnt', parentOnly=True)[0]
    mc.parent(new_jnt, w=True)
    

    Just another minor note: most (if not all) maya commands allow you to pass in an object to modify and also return the name of the "new" object. By storing it in a variable, you can then pass the variable around instead of the string for the object name. This is especially helpful if an object already exists by that name and maya names it with a 1 at the end (ex: 'my_object1'). That way you're not having to manage selections and worry about names which could lead to commands operating on the wrong objects - and that can be very difficult to track bugs...

    So you could write your original code like this:

    import maya.cmds as mc
    
    new_jnt = mc.duplicate('spine02_Joint',n='spineGrpJnt')[0]
    mc.parent(new_jnt, w=True)
    childJnts = mc.listRelatives(new_jnt, ad=True, pa=True)
    mc.delete(childJnts)