Python Code Check - Maya

Hello,
I am learning python with Maya. The problem I have with the following code is that the shader is
deselected when objects are selected. If I reverse command order, objects are deselected when shader is selected and thus can’t make shader assignment. I’m sure the code is basic, but all the code I have found thus far is more complicated, and when I paste it into script editor, I get errors that I can’t seem to solve at my level. Any advice is appreciated.

CODE

import maya.cmds as mc

mc.polyCube(h=5, w=3, d=3)
mc.polySphere(n='bola')
mc.move(0,7,0)
mc.duplicate()
mc.move( 0, 3, 0, relative=True)
mc.duplicate( st=True )
mc.duplicate( st=True )
mc.shadingNode('blinn', asShader=True)
mc.select('blinn1')
mc.select(allDagObjects=True)
#mc.sets() COULD BE HELPFUL - NOT NECESSARY
mc.hyperShade( 'blinn1', assign=True )
###ERROR MESSAGE #Error: line 1: No shader is selected to be assigned
### CAN'T SELECT OBJECTS & SHADER AT SAME TIME - WHAT IS WORKAROUND?
```

mc.select('blinn1') selects the shader only
mc.select(allDagObjects=True) selects all the dag objects (which won’t include shaders – it’s only scene objects apart from the built in cameras). So you’re telling maya to replace the selection .

you can add the selection using the add flag:

mc.select('blinn1')
mc.select(allDagObjects=True, add=True)\

Should select all your scene objects and your shader.

add=True would not work for me,
but this code did work:

import maya.cmds as mc
mc.polyCube(h=5, w=3, d=3)
mc.polySphere(n=‘bola’)
mc.move(0,7,0)
mc.duplicate()
mc.move( 0, 3, 0, relative=True)
mc.duplicate( st=True )
mc.duplicate( st=True )
blinnShade=mc.shadingNode(‘blinn’, asShader=True)
mc.setAttr(“blinn1.color”, 1, 0, 0, type=‘double3’)
mc.select(allDagObjects=True)
mc.hyperShade(assign=blinnShade)
mc.select(clear=True)

I don’t know why it works with the variable - is it how maya thinks or order of execution?
I dunno - but thanks for your quick response.

The names matter a lot – if you hard code blinn1 but you already have a blinn1 in your scene, you may not get what you’re expecting. It’s best to always capture the results of creation commands in variables because Maya will rename things to make them unique.

1 Like