Prevent 'Invalid Path' error when renaming a hierarchy
Say we have a hierarchy like this, and we want to rename them all:
object
ㄴobject
ㄴobject
Since the name 'object' is not unique, we need to use the long names of the objects:
|object
ㄴ|object|object
ㄴ|object|object|object
Now, say we want to rename them, maybe as 'object_01'
, 'object_02'
, 'object_03'
. We can select the objects and run:
for i, obj in enumerate(cmds.ls(sl=True, l=True), 1):
cmds.rename(obj, f'object_{i:02d}')
This is going to result in an error, however. # RuntimeError: No valid object to rename was specified. #
This is because we're altering the path during the iteration; |object|object
will no longer exist since its parent has been renamed to |object_01
.
The easiest (I think) way to prevent this error is to rename the children first. This can be done by sorting the objects by the number of '|'
in their names.
In this case we need to store the index in a tuple, since we still want the first selected object to be named 01
:
sel = cmds.ls(sl=True, l=True)
sel_index = list(enumerate(sel, 1)) # (1, '|object')
child_first = sorted(sel_index, key=lambda x: x[1].count('|'), reverse=True)
for i, obj in child_first:
cmds.rename(obj, f'object_{i:02d}')
This logic also works with shapes, although renaming its transform will overwrite its name without the ignoreShape
flag.