Maya预渲染脚本适配:如何调整材质赋值代码末尾两行使其生效?
hyperShade() Needed) Got it, let's break down why your script works manually but fails as a pre-render script, then fix those final two lines.
The Root Problem
When you run the script manually, selecting objects and using that selection to assign a shader works because you're in an interactive Maya session where the selection state is stable and directly tied to your input. But pre-render scripts run in a non-interactive context—Maya might reset the selection state, or the render process doesn't respect manual selection commands like cmds.select() the same way. Relying on selection for shader assignment is unreliable here.
The Fix: Skip Selection, Assign Directly
Instead of selecting all associated shapes first, iterate over each shape in your associatedShapes list and assign the shader directly to it. Here are two robust approaches (no hyperShade() required):
Option 1: Assign via Shading Group (Permanent Shader Swap)
Maya links shaders to objects through shading groups. Get the shading group for your occlusionShader, then add each shape to that group:
# Get the shading group connected to your occlusion shader occlusion_shading_group = cmds.listConnections(occlusionShader, type="shadingEngine")[0] # Assign each shape to the shading group for shape in associatedShapes: cmds.sets(shape, edit=True, forceElement=occlusion_shading_group)
Option 2: Assign as Render Override (Temporary Swap for Render)
If you only want the shader active for the render (and keep the original material intact), use Maya's override attributes:
for shape in associatedShapes: # Enable shader override for the shape cmds.setAttr(f"{shape}.overrideEnabled", 1) # Assign the occlusion shader as the override cmds.setAttr(f"{shape}.overrideShader", occlusionShader, type="string")
Why This Works
Both approaches bypass the selection system entirely. They directly target each shape node and apply the shader assignment, which works consistently in both interactive and non-interactive (pre-render) contexts. No more relying on unstable selection states!
Just make sure:
associatedShapescontains shape nodes (not transform/top-level objects)—only shapes can be linked to shaders.occlusionShaderis a valid shader node name (double-check it exists in your scene).
内容的提问来源于stack exchange,提问作者mechaniac

