Maya Python脚本异常:将SBSAR纹理应用至全部对象而非选中对象
解决Substance脚本将材质应用到所有对象的问题
问题根源
脚本出现这个问题有两个关键原因:
- 获取目标几何体时用了
cmds.ls(geometry=True),这行代码会返回场景中所有几何体,而非你选中的对象。 - 成功找到材质组(shading group)后,没有执行将材质组绑定到目标几何体的代码,逻辑链不完整。
修复后的完整脚本
import maya.cmds as cmds def _connect_place2d(substance_node): """ Connects the place2d texture node to the Substance node """ place_node = cmds.shadingNode('place2dTexture', asUtility=True) connect_attrs = [('outUV', 'uvCoord'), ('outUvFilterSize', 'uvFilterSize')] for out_attr, in_attr in connect_attrs: cmds.connectAttr('{}.{}'.format(place_node, out_attr), '{}.{}'.format(substance_node, in_attr)) def _find_shading_group(node): """ Walks the shader graph to find the shading group """ result = None connections = cmds.listConnections(node, source=False) if connections: for connection in connections: if cmds.nodeType(connection) == 'shadingEngine': result = connection else: result = _find_shading_group(connection) if result is not None: break return result def _apply_substance_workflow_to_selected(substance_file, workflow): """ Imports a mesh into Maya and applies the shader from a Substance workflow to it """ # 只获取选中的几何体,过滤非网格对象 geometry = cmds.ls(selection=True, geometry=True) # 如果没有选中对象,直接返回避免报错 if not geometry: cmds.warning("请先选中要应用材质的网格对象!") return # Create the substance node and connect the place2d texture node substance_node = cmds.shadingNode('substanceNode', asTexture=True) _connect_place2d(substance_node) # Load the Substance file cmds.substanceNodeLoadSubstance(substance_node, substance_file) # Apply the workflow cmds.substanceNodeApplyWorkflow(substance_node, workflow=workflow) # Acquire the shading group and apply it to the mesh shading_group = _find_shading_group(substance_node) # 将材质组绑定到选中的几何体 if shading_group: cmds.sets(geometry, forceElement=shading_group) else: cmds.warning("未找到对应的材质组!") def demo_load_sbsar_workflow(): """ Acquires an sbsar from a file dialog, loading and applying it to any selected mesh """ file_filter = 'Substance (*.sbsar);;' files = cmds.fileDialog2(cap='Select a Substance file', fm=1, dialogStyle=2, okc='Open', fileFilter=file_filter) if files: substance_file = files[0] _apply_substance_workflow_to_selected(substance_file, cmds.substanceGetWorkflow()) if __name__ == '__main__': demo_load_sbsar_workflow()
关键修改点
- 获取选中对象:把
geometry = cmds.ls(geometry=True)改成geometry = cmds.ls(selection=True, geometry=True),确保只处理你选中的网格,同时增加了空判断避免无选中时报错。 - 绑定材质组:在找到
shading_group后,添加cmds.sets(geometry, forceElement=shading_group),强制将材质组分配给选中的对象,补全了材质应用的最后一步。
内容的提问来源于stack exchange,提问作者Rai Rai
相关产品推荐
相关产品推荐

