Search code examples
pythonmaya

why am i getting an object invalid error?


I think there is something wrong with my naming convention but I'm not sure how to fix it. it keeps giving me an invalid object even when tried to name it based on the vertex please help.

for i in range(1,100):
    print i

def cactus():
#creating base of cactus
    cmds.polyCylinder(sc=1,sa=10,sh=10, n= "cactus1_Base["+str(i)+"]")

The error I'm getting is:

# Error: TypeError: file <maya console> line 17: Object cactus1_Base[99].e[140:169] is invalid this is the error im getting and the code is

Solution

  • I dont have maya this week so I cant really check the result of this code The first piece of codes woulld be for me the best solution but you have also the second one.

    Note that in your code, character '[' and ']' are reserved in maya for components : vtx[], e[], f[]...etc so you cant use them for naming

    Secondly when you create your iteration 'i', it is outside your function so there is no real connection between i and your function cactus() So you have to think on how you want to create cactus. That why I have written those two examples : the first consider that you are creating cactus elements the second one is just for creating a bunch of cactus

    You could go beyond with kwargs and try to mimic cmds.polyCylinder

    Just in case a bit python lessons for maya : https://www.youtube.com/watch?v=PDKxDbt6EGQ&t=4s

    def nameChecker(name, start=0, max=100000, stringFormat=True):   
        if not '{' in name:
            stringFormat = False
        a = start
        while a < max:
            if stringFormat:
                confName = name.format(a)
            else:
                confName = name + str(a)
            if not cmds.objExists(confName):
                return confName
            a+=1
    
    def create_cactus(baseName='cactus1_Base_{:03d}'):
        name_conform = nameChecker(baseName)
        cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name_conform)[0]
        return cactus
    
    cactus_output = []
    for i in range(1,100):
        cactus = create_cactus()
        cactus_output.append(cactus)
    print(cactus_output )
    

    OR more simple :

    def create_cactus(nb_of_cactus=100):
        cactus_output = []
        for nb in range(nb_of_cactus):
            name = "cactus1_Base_{}".format(nb)
            cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name)[0]
            cactus_output.append(cactus)
        return cactus
    myCactus= create_cactus(100)
    print(myCactus)
    

    or based on selection :

    def create_cactusVtx():
        mysel = cmds.ls(sl=True, fl=True)
        for i in range(len(mysel)):
            id = mysel.split('[')[-1][:-1]
            name = "cactus1_Base_{}".format(i)
            cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name)[0]