For Loop to Duplicate Objects in Maya - Python 2
I have been using Maya for over 5 years now and now I want to start scripting certain actions that I want to perform in Maya using python. I have scripting experience in JS.
Let's take a quick look at what I've already done:
I wanted to create multiple objects in Maya using a python for loop to change their position or rotation. I have been successful in this.
Now I want to select an object by name in Maya and duplicate it, rotate / move / scale it using a for loop. The problem I am facing is that I cannot change the name of the object I am targeting when I duplicate it.
Typically using JS I would just use "i" and add it to the end of the name in the "nameOfObject" + i loop
Python only allows the name to be a string, and entering an integer value is giving me a syntax error.
Is there a way to accomplish this action?
My code:
import maya.cmds as cmds
from random import randint
for i in range(0,50):
cmds.duplicate('solitude')
cmds.rotate(0,i*20,0)
It creates 50 of the same objects, but I need to select the newly created object without hardcoding everything.
source to share
I know you've already accepted the answer, and it will work to use the iterator number in conjunction with the source node name - if you don't have multiple duplicates in the scene yet ...
A more "bulletproof" solution would be to grab what the duplicate command is returning to a variable and then use that element for your rotation. This way, you don't have to create the name of the duplicate as you already have it, no matter what maya chose to name it.
If you need to do something, you can also make your choice to use the node as the source before doing duplication and rotation. Thus, you can use the following code by selecting an item and then running the code.
import maya.cmds as mc
src = mc.ls(sl=True)[0]
dup = src
for i in xrange(50):
dup = mc.duplicate(dup)[0]
mc.rotate(0,i*20,0, dup)
also, minor note - it seems that you are not using it randint
in your code ... you can use it elsewhere, though ...
source to share