# =======================================================
# Maya Python Script
# Rename Selected Objects
# BaseName_0001_Suffix
#
# Example:
# SM_Chair_0001_GEO
# SM_Chair_0002_GEO
# SM_Chair_0003_GEO
#
# Automatically increments if names already exist
# =======================================================
import maya.cmds as cmds
# -------------------------------------------------------
# Find Next Available Number
# -------------------------------------------------------
def get_next_available_name(base_name, suffix):
number = 1
while True:
# Format number as 4 digits
number_str = str(number).zfill(4)
# Build name
new_name = "{}_{}_{}".format(
base_name,
number_str,
suffix
)
# Check if object already exists
if not cmds.objExists(new_name):
return new_name
number += 1
# -------------------------------------------------------
# Rename Logic
# -------------------------------------------------------
def rename_objects_execute(*args):
# Get selected transforms
sel = cmds.ls(selection=True, type="transform")
if not sel:
cmds.warning("Please select one or more transform nodes.")
return
# Get UI values
base_name = cmds.textField(
"baseNameField",
q=True,
text=True
).strip()
suffix = cmds.textField(
"suffixField",
q=True,
text=True
).strip()
# Validation
if not base_name:
cmds.warning("Please enter a base name.")
return
if not suffix:
cmds.warning("Please enter a suffix.")
return
renamed_count = 0
# Rename all selected objects
for obj in sel:
# Get unique name
new_name = get_next_available_name(
base_name,
suffix
)
# Rename
renamed = cmds.rename(obj, new_name)
print(
'Renamed: {} -> {}'.format(obj, renamed)
)
renamed_count += 1
print(
"\nFinished. {} object(s) renamed.\n".format(
renamed_count
)
)
# -------------------------------------------------------
# UI
# -------------------------------------------------------
def rename_tool_ui():
window_name = "renameWithNumbersToolWin"
# Delete existing window
if cmds.window(window_name, exists=True):
cmds.deleteUI(window_name)
# Create window
cmds.window(
window_name,
title="Rename With Incrementing Numbers",
widthHeight=(420, 180)
)
cmds.columnLayout(
adjustableColumn=True,
rowSpacing=10
)
cmds.text(
label="Rename Selected Transform Nodes"
)
cmds.separator(style="in")
# Base name
cmds.text(
label="Base Name:",
align="left"
)
cmds.textField("baseNameField")
# Suffix
cmds.text(
label="Suffix:",
align="left"
)
cmds.textField("suffixField")
cmds.separator(style="in")
# Execute button
cmds.button(
label="Rename Objects",
height=40,
command=rename_objects_execute
)
cmds.showWindow(window_name)
# -------------------------------------------------------
# Launch
# -------------------------------------------------------
rename_tool_ui()