2015-10-05 89 views
0

我想創建一個變量來保存Maya中我的定位器和網格物體的列表。所以我有這個在Maya中創建變量時出錯

locators = cmds.listRelatives(cmds.ls(type= 'locator'), p=1)# Give me the list of locators 
meshes = cmds.listRelatives(cmds.ls(type= 'mesh'), p=1) #Give me the list of all meshes 

但是,這些只是傾向於工作,如果在當前場景中有可用的定位器或聚合物。 Maya吐出一個錯誤:

line 1: Object [] is invalid 

如果沒有定位符或聚合找到。

即使它們在現場可用,如何保存它們以使其工作?目的是創建搜索和替換工具。所以如果藝術家願意,藝術家可以只搜索和替換網格。但是現在即使我只有S & R網格,它也會出錯。定位器在搜索網格時發生錯誤,當我查找定位器時網格失敗。

下面是我的整個搜索和替換代碼:

def searchAndReplace(self): 
    searchText = str(self.windowObj.myLookFor.text()) #My search text feild 
    replaceText = str(self.windowObj.myRepFor.text()) #My replace text feild 
    selection = cmds.ls(sl=True) #only selected items 
    locators = cmds.listRelatives(cmds.ls(type= 'locator'), p=1)# Give me the list of locators 
    meshes = cmds.listRelatives(cmds.ls(type= 'mesh'), p=1) #Give me the list of all meshes 
    joints = cmds.ls(type = 'joint')# Give me the list of my joints. 
    allObjects = locators, meshes, joints 

    if len(selection) > 0: 
     if self.windowObj.myRepAll.isChecked(): 
      print "All is selected" 
      for object in meshes: 
       if object.find(searchText) != -1: 
        newName = object.replace(searchText, replaceText) 
        cmds.rename(object, newName) 
        self.listofMeshes.append(meshes) 
       else: 
        print "No mesh found. Skipping meshes" 
      for object in locators: 
       if object.find(searchText) != -1: 
        newName2 = object.replace(searchText, replaceText) 
        cmds.rename(object, newName2) 
        self.listofLocators.append(locators) 
       else: 
        "No locators found. Skipping locators" 
      for object in joints: 
       if object.find(searchText) != -1: 
        newName3 = object.replace(searchText, replaceText) 
        cmds.rename(object, newName3) 
        self.listofJoints.append(joints) 
       else: 
        print "No joints found. Skipping joints" 

需要幫助的在商店中的變量正確,因此它可以正確地存儲定位器,網格和關節,並能夠使用它,如果他們中的一個不可用在現場。

回答

0

當我運行你在一個新的空場景中指出的兩個語句時,我在兩個變量上都得到一個None。

在這種情況下,你開始循環之前,你可以防止錯誤每個for循環縮進到,例如,如果網:,甚至更好,一個如果isinstance(網格,列表):,這要是網格是一個列表將只執行代碼:

if isinstance(meshes, list): 
    for object in meshes: 
     if object.find(searchText) != -1: 
      newName = object.replace(searchText, replaceText) 
      cmds.rename(object, newName) 
      listofMeshes.append(meshes) 

如果你仍然在嘗試執行語句,縮進是爲try/catch塊看到更詳細的解釋,當同樣的錯誤發生了什麼事,並從Maya CMDS' documentation獲得更多幫助:

try: 
    locators = cmds.listRelatives(cmds.ls(type= 'locator'), p=1) 

except Exception as e: 
    print e 
0

默認情況下,如果cmds.listRelatives找不到任何東西,而不是像預期的那樣返回空的[],它將返回None

兩種方法來解決,這將是要麼轉換None[]

print cmds.listRelatives(cmds.ls(type= 'locator'), p=1) or [] 
> returns [] 

或做健康檢查,看是否該變量爲空:

sceneLocators = cmds.listRelatives(cmds.ls(type= 'locator'), p=1) 
if sceneLocators: 
    print 'Continue' 
else: 
    print 'No locators!' 

你不應該包裝一個tryexcept像卡洛斯建議。這在編程方面只是一些不好的做法,有些例外,通常是一些懶惰的方式去做事情。