well, that’s kind of it – alas. Maya’s decision to use names as ids has lots of negative consequences, but there’s no easy way around it.
I think your example code may be redundant: if you just capture the rename, you’ll get back a numeric increment automatically (although with no suffix).
The truly sucky thing, however , is that Maya will mess with your objects as you move them around in the hierarchy. So, you can make an object, call it anything you like – but when if you parent it into a location where there’s an existing object with the same short name, your original will get renamed on you whether you like it or not.
Some rules for living in a universe where this happens:
#1: Don’t use names for anything important. Naming conventions don’t work as a primary tools in a world where stuff changes names just because somebody did something as simple as parenting or unparenting.
#2: always, always use the long form of names for anything longer than a 3 line script – and doubly always if you’re passing stuff between functions. ls(l=True) is and listRelatives (f=True) are your friends
#2: Use sets or selections as name-independent ways to keep track of things. If you need to work on a bunch of stuff whose names may be in flux due to renaming or hierarchy changes. If you have a selection, you can iterate over it getting names at the last second and removing items as you process them:
sel = cmds.ls(sl=True)
while sel:
last = sel.pop()
cmds.select(cmds.rename(last, 'renamed'), d=True)
sel = cmd.ls(sl=True)
of course in that case, the names are all different so there’s no way to recover the end result. Sets is a nice way to handle that:
def rename_to_set(*objs):
sel = cmds.ls(sl=True)
result = cmds.sets(n='my_stuff') # use a variable - you don't know what name you'll get !!
while sel:
last = sel.pop()
cmds.select(cmds.rename(last, 'renamed'), d=True)
sel = cmd.ls(sl=True)
return result
#3: To identify stuff permanently, attributes are a good way to go. You have control over the visibility and editability. Don’t want your users to change a ‘left_hand’ to ‘right_hand’ by accident? just lock the ‘.side’ attribute, etc. ls(o=True, “*.myAttrib”) is a simple cheap way of finding things again.
#4: Never assume stuff got the name you expected (your example shows you already get that part…) If you need to be sure something came out the way you wanted, always stick the result into a variable:
newNode = createNode('transform', name='newnode')
and you can verify it with ls:
newnode = cmds.createNode('transform', name= 'i_want_this_name')# item is selected after creation
assert 'i_want_this_name' in cmds.ls(sl=True) # raises if the name didn't turn out as expected