Skip to content

Adding objects at random places in Maya with Python

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 would just just need to amend the above import to:

‘import random as rn’

Or something similar.


Now lets create a variable to store the target number of objects, and also a variable which we can use to deteremine when to stop the loop.

# 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:

  1. While the value of count is less than the target number of cubes we want.
  2. Create a cube
  3. Get the ‘Name’ of the new cube (We need this to be able to apply the attributes)
  4. Set each of the translate attributes to a random value between -10 and 10
  5. 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.

The above example in action

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

Published inMayaObject ManipulationObjectsPythonscripting