在 Maya 中更新对象名称时出现问题 Python

Problem with updating object names in Maya Python

对于我的脚本 class,我一直在研究创建控制曲线的 Maya Python 脚本。该脚本在我创建第一个和第二个对象时起作用。但是,如果我创建更多具有相同名称的对象,该名称将无法像我希望的那样工作。现在,对象名称如下:PREF_NAME_SUF、PREF_NAME_SUF1、PREF_NAME_SUF11、PREF_NAME_SUF111 等

我该怎么做 PREF_NAME_SUF、PREF_NAME_SUF1、PREF_NAME_SUF2、PREF_NAME_SUF3 等?

这是我目前拥有的:

    def createCurves(controlName):
        if cmds.objExists(curveObject):
            print("Warning: This name already exists.")
            oldCurveObject = curveObject
            print oldCurveObject, curveObject
            for i in range(1):
                i = i+1
                print controlName + str(i)
                controlName = oldCurveObject + str(i)

您可以使用模块 re 提取名称。

import re

controlName = 'PREF_NAME_SUF1'

pattern = re.compile('\d+$') # finish by a number

r = pattern.search(controlName) # we search the string, if there is no result, we will do special operations

if r:
    new_number = str(int(r.group(0)) + 1) # from our search we extract the number
    new_name = pattern.sub(new_number, controlName) # we replace the end number by the new one
else:
    if cmds.objExists(controlName):
        # if the control exists already we append 1 to the name
        new_name = controlName + '1'
    else:
        # if it doesn't exists, we dont add an iteration number
        new_name = controlName

_____ 编辑 _________

您并不真正理解控件的命名方式。 你需要一起生成你的三个名字,否则你会创建重复的名字,让 maya 做错了。 还尝试删除调试打印,也可能删除全局变量并使用更多 return

def createCurves(controlName):

    # if the control exists already we append 1 to the name
    name_pattern = re.compile( controlName + '(\d+)?$') # it doesn mean your ControlName can have a number but it is not mandatory
    tr = cmds.ls(type='transform') # we list all transform
    number_finder = [name_pattern.findall(i)[0] for i in tr if name_pattern.findall(i)] # we find if the name already exists
    # if we find something, we work on the iteration 
    if number_finder:
        last_number = sorted(number_finder)[-1]
        if last_number != '':
            new_number = str(int(last_number) + 1)
        else:
            new_number = '1'
    else:
        # if nothing we don&t need to iterate
        new_number = ''
    
    new_name = controlName + new_number

    new_offname = controlName + ccOFFName + new_number
    new_grpname = controlName + ccGRPName + new_number   
    
    #create the curve according to which shape is selected
    if (selectedShapeValue == 'Circle'):
        created_curve, createNode = cmds.circle(n= new_name)
    
    if (selectedShapeValue == 'Square'):
        created_curve = cmds.curve(n= new_name, d = 1, p = [(-1, 0, 1),(-1, 0, -1), (1, 0, -1),(1, 0, 1),(-1, 0, 1)], k = [0, 1, 2, 3, 4])
    
    if ccOFFcheck:
        cc_OFF = cmds.group(created_curve, n = new_offname)
        
    if ccGRPcheck:
        cc_GRP = cmds.group(cc_OFF, n = new_grpname)
        
        
    return new_name

在这段代码中,我根据一个假设生成名称:您的控件名称依赖项必须是唯一的 现在您还生成了三个名称,最后是迭代编号。