Learning how to loop with Python

Hi guys would appreciate some help :slight_smile:

trying to write a script that connects the shapes of a referenced in shape under a transform to a similar shape that is already in the scene. Struggling with transforms that have more than one shape, the point is using the selected reference transform - striping the namesspace to identify the selected target and connecting the shapes of the referenced shape curves to the targets within the scene

S.

    #print name of selection and split it from nameSpace to identify targetShape

    import maya.cmds as mc

    lSelection = cmds.ls(sl=True)
    lShapes = mc.listRelatives(lSelection, s=True)
    print lShapes 
      
    for obj in lShapes: 
        nameS = obj.split(':')[0]
        print (nameS)
        targetShapes = obj.split(':')[-1]
        print (targetShapes)
        
    cmds.connectAttr(lShapes + '.worldSpace', targetShapes + '.create' )

Ok, before I answer, I must address a pet peeve: Try not to use short flags for any code that you expect to use more than once. Doesn’t matter how well you know the commands, use the long name. Your future self, and anybody else that ever looks at your code will thank you. Specifically change s to shapes in mc.listRelatives. I will grudgingly accept mc.ls(sl=True) though.

Now for the actual answer.
First thing, you’re confusing yourself with a variable name. The variable targetShapes should be targetShape. Singular instead of plural because that variable only ever holds one object at a time. It’s not a list. Naming things like that isn’t requirement, but it helps you remember what things are expected to be lists, and what things aren’t.

So now that you know targetShape isn’t a list, think about it like this: You want to connect every obj to every targetShape. So connectAttr has to get called more than once. That means your connectAttr has to be in the loop too!

Other things I see:
You’re getting the namespace and then never using it. You could just remove that code.
Also, you used cmds.ls instead of mc.ls. Doesn’t matter which one you choose, just stay consistent.

    import maya.cmds as mc

    lSelection = mc.ls(sl=True)
    lShapes = mc.listRelatives(lSelection, shapes=True)
    print lShapes 
      
    for obj in lShapes: 
        targetShape = obj.split(':')[-1]
        cmds.connectAttr(obj + '.worldSpace', targetShape + '.create' )
3 Likes

cheers dude! this helps loads will report if I run into anymore issues! :slight_smile:

Something small, but I wanted to point it out because I use it all the time with namespaces is the python rpartition() method. You can use it in place of split when you want to split a node name and parent namespace since it will handle nested namespaces and is a little bit faster since it only has to find a single token.

3 Likes