My goal is to set a shader to each parts of a geo. The parts of the geo are typically a group of attached faces. I do this to bake an ID map and then use it in Substance Painter.
So far, I separate the parts, then assign a shader to each and unite them back. I eventually delete the history to clean the outliner and the mesh itself.
import maya.cmds as mc
import random
selection = mc.ls(sl=True)[0]
parent = mc.listRelatives( selection, ap = True)[0]
mc.polySeparate(selection)
parts = mc.ls(sl=True)
for p in parts:
sha = mc.shadingNode('lambert', asShader=True, name=p+"_lambert")
sg = mc.sets(empty=True, renderable=True, noSurfaceShader=True, name=p+"_SG")
mc.setAttr(sha+".color", random.uniform(0.0, 1.0), random.uniform(0.0, 1.0), random.uniform(0.0, 1.0))
mc.connectAttr( sha+".outColor", sg+".surfaceShader", f=True)
mc.sets(p, e=True, forceElement=sg)
result = mc.select( selection, r = True )
sel = mc.ls( sl=True )
parts = mc.listRelatives( sel[0], c = True )
mc.polyUnite(parts, muv = True, name = selection)
mc.DeleteHistory()
I've got my shaders on parts but lose my original group under which the mesh was parented, and it doesn't feel right to do it this way.
Is there a way to create sets of parts without using 'separate' and assign a shader to each set?