4

I am trying to make a simple "allign tool" in maya using Python script, and this is how far I got

import maya.cmds as cmds

selected = cmds.ls(selection=True)

for all in selected:

         cmds.getAttr('Cube.translateX')

And this seems to get the X position of the object names cube in the scene, However I would like it to get the translate of any object I selected.

I hope someone can help out, thanks

galaxy
  • 53
  • 1
  • 1
  • 15
Chico Spans
  • 41
  • 1
  • 1
  • 2

3 Answers3

3

In the string 'Cube.translateX', you need to have the selected object's name in place of 'Cube'. We do this by a simple string formatting here using the %s format:

import maya.cmds as cmds

selected = cmds.ls(selection=True)

for item in selected:
    translate_x_value = cmds.getAttr("%s.translateX" % item)
    # do something with the value. egs:
    print translate_x_value

Hope that helped.

kartikg3
  • 2,590
  • 1
  • 16
  • 23
2

@kartikg's answer will work fine. As an alternative, maya's default behavior is to use selected objects by default for commands which need objects to work on. So:

original_selection = cmds.ls(sl=True)
for item in selected:
    cmds.select(item, r=True) # replace the original selection with one item
    print cmds.getAttr(".translateX")  # if the name is only an attribute name, Maya
                                        # supplies the current selection

This is useful when you want to do a series of commands on every object in the list, since you don't have to type the string formatter for every command. However @kartikg's method is easier to read and debug since you can check it by replace the command with a print statement.

Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
theodox
  • 12,028
  • 3
  • 23
  • 36
  • @theodoxx, did not know that `cmds.getAttr(".translateX")` would work on current selection without attribute passed. Tried it out with multiple objects selected and it spit out a list. Pretty neat! Thanks for the info! – kartikg3 Nov 11 '14 at 21:00
0
import maya.cmds as cmds                                
objects = cmds.ls(sl=True)                              
for o in objects:                                          
    x_translate = cmds.getAttr(o + '.translateX')  
    print (x_translate)
Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
Ari Gold
  • 1,528
  • 11
  • 18