返回列表
mayaAPI

cmds打组解组脚本详解2

该脚本是Maya场景层级自动化清理工具。

transNodes = cmds.ls(type="transform", long=True)
print(transNodes)

1.type="transform":只获取变换节点

2.long=True:返回完整路径,避免重名节点导致错误。

目的:拿到场景里所有 可作为组 / 父节点的对象。

groupList = []

for node in transNodes:
shapeNode = cmds.listRelatives(
node,
shapes=True
)

# 如果没有子形状节点,则视为组
if not shapeNode:
groupList.append(node)

1.listRelatives(…, shapes=True):查询节点是否有形状节点

2.if not shapeNode

*有形状 = 模型 / 实体

*无形状 = 纯组

目的:精准筛选出所有空组 / 层级组,不包含任何实体模型

groupChildren = []

for group in groupList:
children = cmds.listRelatives(
group,
children=True,
fullPath=True
)
groupChildren.extend(children)
  1. children=True:获取组的直接子物体。
  2. fullPath=True:获取完整路径,保证解组时不会找错物体。
  3. extend():把所有组的子物体汇总到一个大列表,统一处理。

目的:收集所有 “需要被解组” 的物体

if groupChildren:
try:
cmds.parent(
groupChildren,
world=True
)
print("解组成功!")
except Exception as e:
print(f"解组失败: {e}")
return
else:
print("没有需要解组的物体")

1.cmds.parent(…, world=True)

*将物体父级设为世界空间

*= 解组,且保持位置不变

2.try/except:异常捕获,防止嵌套、权限、节点丢失导致脚本崩溃。

3.判断列表是否为空:没有子物体时直接退出,避免无效执行。

目的:一次性批量解组所有组内物体。

for group in groupList:
# 检查节点是否还存在
if cmds.objExists(group):
children = cmds.listRelatives(
group,
children=True
)
print(f"删除空组: {group}")
cmds.delete(group)

1.objExists:先判断节点是否还存在,防止已被删除导致报错。

2.再次检查子物体:确保组真的空了,才删除。

目的:解组完成后自动删除空组,干净清理场景层级。