Search code examples
pythonmaya

Creating a Hierachy in Maya


I've written some code for a tool that duplicates and moves controllers/objects to joints. Its really just code to copy and move one object to a list of other objects. Its very basic but it does work.
The pasted code is a snippet that I've taken out from the rest but will work if run in Maya. This code in particular will create a nurbsCurve, put it inside a group, then move that group to the first object on the list. I then used a loop to do it again, but then parent the group underneath the nurbsCurve from the previous group to create a parent-hierarchy all the way down.

import maya.cmds as cmds

def setZero(target):
    cmds.setAttr("%s.translateX" % target, 0)
    cmds.setAttr("%s.translateY" % target, 0)
    cmds.setAttr("%s.translateZ" % target, 0)
    cmds.setAttr("%s.rotateX" % target, 0)
    cmds.setAttr("%s.rotateY" % target, 0)
    cmds.setAttr("%s.rotateZ" % target, 0)

selJoint = cmds.ls(selection = True, shortNames = True)

firstCtrl = cmds.circle(normal =( 1,0,0))
firstGrp = cmds.group(firstCtrl)
cmds.parent(firstGrp,selJoint[0])
setZero(firstGrp)
cmds.parent(firstGrp, world = True)
#Use loop for the rest of the joints
for joint in selJoint:
    #Skip the first joint since its already done
    if joint == selJoint[0]:
        continue
    circleCtrl = cmds.circle(normal =( 1,0,0))
    offsetGrp = cmds.group(circleCtrl)
    cmds.parent(offsetGrp, joint)
    setZero(offsetGrp)
    cmds.parent(offsetGrp, world = True)
    cmds.parent(offsetGrp, firstCtrl) #Parent new offset Group to the old controller
    firstCtrl = circleCtrl #The new controller is now the target for the next offset/ctrl to be parented under

It works as intended but I get this warning:
Warning: Cannot parent components or objects in the underworld
I've tried looking this issue up, but I haven't found anything on how to fix the problem. But I do know that the "underworld" is another space in Maya, and that it can cause issues down the line.


Solution

  • The warning is being thrown at the end on this line cmds.parent(offsetGrp, firstCtrl), and if you print out firstCtrl it'll output something like this:

    [u'nurbsCircle1', u'makeNurbCircle1']

    So what it's doing is it's trying to parent firstCtrl and 'nurbsCircle1' to 'makeNurbCircle1'. Since 'makeNurbCircle1' is a node with no transform, it throws that warning, because obviously you can't parent to something with no transform.

    Luckily it's very easy to fix. Now that we know that it's a list, we just parent to the first index of it like so: cmds.parent(offsetGrp, firstCtrl[0])

    If you want more info on this same warning then you can also check out this question.