MAYA Python Script, getting the position of the selected object using GetAttr

I am trying to do a simple "allign tool" in Maya using a Python script and this is how far I got

import maya.cmds as cmds

selected = cmds.ls (selection = True)

for all those selected:

    cmds.getAttr('Cube.translateX')

      

And it's like getting the X-position of the cube of object names in the scene, but I would like it to get the translation of whatever object I choose.

I hope someone can help, thanks

+3


source to share


3 answers


In the line 'Cube.translateX' you need to specify the name of the selected object instead of 'Cube'. We do this by 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 it helped.

+2


source


@ kartikg's answer will work fine. Alternatively, maya's default behavior is to use default selected objects for commands that need objects to work with. 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 make a series of commands for each item in the list, since you do not need to enter a string formatter for each command. The @kartikg method is easier to read and debug, however, as you can test it by replacing the command with a print statement. In the meantime, there is no need to know about it. ”

+1


source


import maya.cmds as cmds                                
objects = cmds.ls(sl=True)                              
for o in objects:                                          
    x_translate = cmds.getAttr(o + '.translateX')  
    print (x_translate)

      

0


source







All Articles