Search code examples
pythonmaya

setAttr function in Autodesk Maya


I am still learning Python in Maya. I cannot get my code to work. I am trying to create a locator and parent it under my selection and then zero out the locators transforms.

import maya.cmds as cmds

sel = cmds.ls(selection = True)
loc = cmds.spaceLocator()
cmds.parent(loc, sel)
cmds.setAttr(loc, "translateX", 0)

I always get this error message:

#Error: TypeError: file <maya console> line 7: Invalid argument 1, '[u'locator6']'. Expected arguments of type ( list, )

Sometimes with a bit other code I get something like:

#There does not exist something with name 'translateX'

I know that it does work when I replace loc with the name of the locator, but I try to keep the code as universal as I can and not bound to the name of a locator.

How does the setAttr function work in Maya with variables? Maya docs and other questions at various forums could not help... :/


Solution

  • setAttr takes one complete attribute as its argument:

     cmds.setAtt( loc + ".translateX", 0)  
    

    where loc has to be a single string. spaceLocator like most creation commands returns a list, not a single string. So the whole thing is:

    sel = cmds.ls(selection = True)
    loc = cmds.spaceLocator()
    cmds.parent(loc, sel)
    cmds.setAttr(loc[0] + ".translateX", 0)