Search code examples
pythonmaya

How create a list colorSets, access them and delete them in Maya?


I am trying to list colorSet names in order to control how many of them I have on a given mesh. I can't seem to pass the right variable to the cmds.ls for it to recognize colorSet

I've read around and it seems like mostly cmds.ls is used for meshes but with correct attributes it can be used to list pretty much anything

import maya.cmds as cmds

colorList = cmds.ls('colorSet*', sl=True, long=True)
objects = cmds.ls( sl=True, long=True)

if len(objects) > 0:
    if len(colorList) > 0:
        cmds.delete(colorList)

    result=cmds.polyColorSet(cr=True, colorSet='colorSet') 
    result=cmds.polyColorSet(cr=True, colorSet='colorSet')

The code ends up ignoring my if statement and continues to create colorSets indefinitely. How do I make my code delete old ones before creating new ones?


Solution

  • You can use cmds.listHistory to get all the inputs from an object, then cmds.ls to filter that result to find any color sets:

    import maya.cmds as cmds
    
    for obj in cmds.ls(sl=True):  # Loop through the selection.
        history = cmds.listHistory(obj)  # Get a list of the object's history nodes, which may include a color set.
        existing_color_sets = cmds.ls(history, type="createColorSet")  # Filter history nodes to only color sets.
        if existing_color_sets:  # If a color set exists, delete it.
            cmds.delete(existing_color_sets)
    
        cmds.polyColorSet(obj, cr=True, colorSet="colorSet")  # Create a new color set.