Vlad
Vlad

Reputation: 77

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.

Upvotes: 0

Views: 1394

Answers (2)

Green Cell
Green Cell

Reputation: 4777

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.

Upvotes: 4

Mike Peder
Mike Peder

Reputation: 738

You might use a dictionary:

spines = "spineA_jnt", "spineB_jnt", "spineC_jnt", "spineA_jb", "spineB_jb", "spineC_jb"
def group_spines(spines):
    spine_dict = {}
    for spine in spines:
        parts = spine.split('_')
        if parts[0] in spine_dict:
            spine_dict[parts[0]].append(spine)
        else:
            spine_dict[parts[0]]=[spine]
    return spine_dict

spine_dict = group_spines(spines)
# results of group_spines function
{'spineA': ['spineA_jnt', 'spineA_jb'],
 'spineB': ['spineB_jnt', 'spineB_jb'],
 'spineC': ['spineC_jnt', 'spineC_jb']}

final_result = dict(spine_dict.values())
# now we have parented the spine parts together 
{'spineA_jnt': 'spineA_jb',
 'spineB_jnt': 'spineB_jb',
 'spineC_jnt': 'spineC_jb'}

Upvotes: 0

Related Questions