Search code examples
pythonduplicatesmaya

How can I repeat the command in for loop?


I'm trying to perform duplicate a sphere in z axis 10 times and then duplicate this whole copied spheres X and Y axis.

And I'm stuck after first step like this. Can I get some advice how I can repeat this duplication to X and Y?

import maya.cmds as cmds

cmds.polySphere(r=0.5, sx=10, sy=10)
for i in range(0, 9):
    cmds.duplicate()
    cmds.move(0, 0, 2, r=True)

Solution

  • If you're trying to make a cube of spheres, you just need 3 loops for each axis. To get the spacing right you multiply whatever the sphere's radius by 2:

    import maya.cmds as cmds
    
    count = 4
    radius = 0.5
    
    for x in range(count):  # Loop in x axis.
        for y in range(count):  # Loop in y axis.
            for z in range(count):  # Loop in z axis.
                # Create a new sphere.
                transform, psphere = cmds.polySphere(r=radius, sx=10, sy=10)
    
                # Move it.
                cmds.move(
                    x * radius * 2, 
                    y * radius * 2,  
                    z * radius * 2, 
                    transform)
    

    This will result like this:

    Cube of spheres