Maya PyMel iterating through layers in a scene and creating groups from the contents

469 Views Asked by At

I am having trouble understanding how to:

  1. iterate through the layers in a scene,
  2. select the contents of each layer,
  3. group all of the contents of the layer into one group
  4. rename the group based on the name of the first obj in the layer +_'grp'

I have some of the concepts down, I just don't seem to be iterating properly when I run this code. I am getting an error on line 5 saying that the 2nd for loop has a NoneType and can't iterate. I tried setting the layer to a value and trying to increment in the loop, but it doesn't seem to work

import pymel.core as pm
layerList = pm.ls(type="displayLayer")
layer = 0
for layer in layerList:
    selection = pm.select(layer)
    for each in selection:
        cmds.select(each, r=True)
        pm.group()
        pm.rename(each+'_grp')
        
     layer +=1
1

There are 1 best solutions below

0
On

The line

selection = pm.select(layer)

does not return anything, it only selects the layer. I suppose you need the content of the layer so

selection = layer.listMembers()

cold help. And this lines:

layer = 0
... and ...
layer += 1

do not make any sense because layer is not a number even if you assign a 0 to it. The for loop assigns the objects from the list to layer not numbers. Usually it is better to not relying on the selections in Maya but use names of the objects wherever possible, so you can do:

group = pm.group(n=each.name()+"_grp")
pm.parent(each, group)