Search code examples
pythonmaya

how to parent objects depends on their in maya via python


I am a bit new to Python and I am trying to parent objects in maya depending on their name. Example I have in scene "spineA_jnt", "spineB_jnt", "spineC_jnt" and "spineA_jb", "spineB_jb", "spineC_jb". How to select them all and parent "spineA_jnt" to "spineA_jb" and so on. Any tips would be really appreciated, thanks.


Solution

  • Looks like you can use your names to your advantage since they share the same name but have a different suffix, so you don't need to hard-code strings.

    Here's an example of parenting _jnt objects to _jb.

    import maya.cmds as cmds
    
    # Use * as a wildcard to get all spine joints.
    jnts = cmds.ls("spine*_jnt")
    
    for obj in jnts:
        # Build name to the object we want it to parent to.
        parent_obj = obj.replace("_jnt", "_jb")
    
        # But skip it if it doesn't exist.
        if not cmds.objExists(parent_obj):
            continue
    
        # Finally parent _jnt to _jb
        cmds.parent(obj, parent_obj)
    

    You can always change "_jnt" or "_jb" if you want to use different names.