How to set attributes on objects in Maya using Python scripting.
Let’s take a look at how we would do this, firstly we’ll set up our script by importing the
from maya import cmds
And we’ll create a cube object:
cube = cmds.polyCube()
Before we move on we need to get the object name, if we print the cube variable we’ll get the following output:
While this list can be useful, it’s not really what we want in this case, we only need the ‘pCube1’ bit, as we’ll use this name to apply the attributes in a moment.
Let’s create another variable, and in
cubeShape = cube
If we print this new variable, we’ll get the output we need:
If we were to change our variable query to:
The output would be ‘polyCube1’, as this is 2nd in the object list.
We can now use this to build our command to set an attribute, for this example lets lock all 3 translate values (X, Y and Z), essentially resulting in a cube object you can’t move.
Let’s break this command down, see what’s going on:
- cmds = From the maya commands library
- .setAttr() = Get the .setAttr method
- cubeShape = We’ve stored our object name in this already (pCube1)
- +”.translate” = This is the attribute are we modifying
- , lock=True = This is the new value of the attribute
The final code
# Import maya commands library from maya import cmds # Create a cube object cube = cmds.polyCube() # This will output a list [u'pCube1', u'polyCube1'] print cube # Get the cube shape from the cube object cubeshape = cube # This will output pCube1 print cubeshape # Lock the translate attrubute cmds.setAttr(cubeshape+".translate", lock=True)