Skip to content

Instantly share code, notes, and snippets.

@justinfx
Last active September 14, 2016 22:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinfx/e06e8496e535badb20e6b4ec5f0f5f77 to your computer and use it in GitHub Desktop.
Save justinfx/e06e8496e535badb20e6b4ec5f0f5f77 to your computer and use it in GitHub Desktop.
Example of an approach to generating a unique name for a Maya object, using Maya commands API
"""
Re: https://groups.google.com/d/topic/python_inside_maya/ndjexeQrZs8/discussion
Example of an approach to generating a unique name for a Maya object.
Author: Justin Israel (justinisrael@gmail.com)
"""
def uniqueNamePattern(base="object", padding=1):
"""
Find the next available Maya object name, starting
with the given base name. Subsequent names will have
a number appended to the end.
A custom position for the number counter can be specified
by using a python format string pattern, like:
"prefix_{0}_suffix"
In this case, the {0} will be replaced with the counter:
"prefix_2_suffix"
If padding is > 1, pad the counter to the given width,
with zeros
"""
i = 1
# Have we been given a string with a format placeholder ({0})?
customRepl = base.format('x') != base
if customRepl:
# Apply custom padding if needed
iStr = str(i)
if padding > 1:
iStr = iStr.zfill(padding)
# Start with our first counter value
name = base.format(iStr)
else:
# Start with the original base value
name = base
# Keep looping while the name exists in Maya
while cmds.objExists(name):
i += 1
# Apply custom padding if needed
iStr = str(i)
if padding > 1:
iStr = iStr.zfill(padding)
# Update name with new version, formatted with
# updated counter value
if customRepl:
name = base.format(iStr)
else:
name = "{0}{1}".format(base, iStr)
return name
# Example usage
cmds.group(name=uniqueNamePattern("test_{0}_GRP"), 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment