Search code examples
pythonloopsmaya

Maya Python - how to iterate through list and attach objects


I am creating a list based on user selection and want for each selected item in the list (object, vertex etc.) create a locator at that items world position:

import maya.cmds as mc
selection = mc.ls(sl=True)

for each in selection:
    newLoc = mc.spaceLocator()
    mySelPosition = mc.xform(selection, q=True, ws=True, t=True)
    mc.move(mySelPosition[0], mySelPosition[1], mySelPosition[2], newLoc)
    

This doesn't work when selecting objects (say two spheres) and it just creates a locator at the origin.

When selecting multiple vertices, it creates as many locators as selected list items, but they are all created at the first item in the list.


Solution

  • Not sure if I follow, but I think your problem is in line 6,

    mySelPosition = mc.xform(selection, q=True, ws=True, t=True)  # your line
    mySelPosition = mc.xform(each, q=True, ws=True, t=True)  # correct line
    

    try this:

    import maya.cmds as mc
    selection = mc.ls(sl=True)
    
    for each in selection:
        newLoc = mc.spaceLocator()
        mySelPosition = mc.xform(each, q=True, ws=True, t=True)
        mc.move(mySelPosition[0], mySelPosition[1], mySelPosition[2], newLoc)