How to get the name of a selected Object Python Maya

Stefano Feltre picture Stefano Feltre · Mar 23, 2017 · Viewed 16.2k times · Source

Hei all, I have this procedural program that creates different object in Maya through Python. After the creation of these elements I want to get the user the possibility to select some of these object and though a button to delete it...The problem is that I don't understand how to get the name of the object... So far my code is this..

#Deletes Selected Element selected from the user
def DeleteSelection(*args):
    selected = cmds.ls(sl=1,sn=True)
    print(selected)
    #if(cmds.objExists()):
        #cmds.delete(selected)
#

And in the GUI I have this button...

cmds.button(label='Delete Selection', w=150,h=30,command=DeleteSelection)

Answer

Achayan picture Achayan · Mar 23, 2017

cmds.ls will return a list, you need to check the list and delete what ever you want to delete, and sn is very bad always use long name because there can be duplicates.

selected = cmds.ls(sl=True,long=True) or []
for eachSel in selected:
   cmds.delete(eachSel)

ps : you should give a try to read doc's since you asked so much basic question. Its not fair to ask very simple things like this.