A quick guide on how to add a defined number of objects at random to a scene in Maya, using Python.
We’ll begin by importing the Maya commands library:
from maya import cmds
But that’s not all we need to import, we also need to import the random package:
import random
If the tool was going to be big, I would recommend creating an alias for ‘random’ to improve readability and decrease how much code you need to write, we
wont be doing that in this example but if we were wouldjust just need to amend the above import to:‘import random as rn’
Or something similar.
Now
# Give us something to increment count = 0 # How many objects we want cubes = 10
We can now create our loop:
# Create some cubes! while count < cubes: # Create the cube cube = cmds.polyCube() cubeshape = cube[0] # Place the cube at random cmds.setAttr(cubeshape+".translateX", random.randrange(-10, 10)) cmds.setAttr(cubeshape+".translateY", random.randrange(-10, 10)) cmds.setAttr(cubeshape+".translateZ", random.randrange(-10, 10)) # Increment the count count += 1
Lets have a quick run through of what’s happening in this loop:
- While the value of count is less than the target number of cubes we want.
- Create a cube
- Get the ‘Name’ of the new cube (We need this to be able to apply the attributes)
- Set each of the translate attributes to a random value between -10 and 10
- Increment the count variable by 1
This will repeat until the value of count is equal to the target number of objects we’ve asked for.
This could be improved on by adding a UI window, in my example for showing a window I have done exactly that, the example window presents the user with a slider and a button, they can choose the number of objects and hit a button to place them into the scene, again at random translate values:
https://github.com/johnplayer1982/python_maya/blob/master/ex_showwindow.py