Python script: Filter object selection by material


#1

hey guys,

I just started out with scripting and at the moment I’m trying to find a way to select all objects with the lambert1 shader assigned, but only within my current selection.I can get them all in the whole scene via the initialShadingGroup and the listConnections and sets command, but I’m struggling getting it done for only the current selection.

Any ideas or help would be awesome.

Cheers,
Sven


#2

Hi,
may be a noob answer but (until you find something more strait…)
why not, after getting them for the hole scene, just check if any of the assigned objects are in your current selection set? you could then isolate those that match


#3

hey sibipf,
thanks for your answer, this would work, but it might be too slow on larger scenes, but I’ll give it a try.
I was actually thinking of going through my list of objects and checking if any of it is connected to the initialShadingGroup and if so, do something (extra code) to it.
I guess I need to use a for loop and if statement for this to work, but I can’t put it together the right way.


#4

Something like this will do what you want I think:

shadingGroup = 'initialShadingGroup'
allSgShapes = set(cmds.listConnections(shadingGroup, type='shape'))
userSelection = set(cmds.ls(selection=True))
userSgShapes = list(userSelection.intersection(allSgShapes))
cmds.select(userSgShapes, r=True)

#5

That works! Thank’s a lot spire2. :thumbsup:
I try to study each line to understand what each line of code is doing, so what I get is:

storing the name (string) ‘initialShadingGroup’ in the variable shading group

shadingGroup = ‘initialShadingGroup’

get all shapes connected to the ‘initialShadingGroup’ and store it in the variable allSgShapes

allSgShapes = set(cmds.listConnections(shadingGroup, type=‘shape’))

store the current selection in the variable userSelection

userSelection = set(cmds.ls(selection=True))

here I guess you get the difference between the current selection and the allSgShapes from the ‘initialShadingGroup’, which leaves us with the wanted selection (= lambert1 only within the selection)

userSgShapes = list(userSelection.intersection(allSgShapes))

select the userSgShapes

cmds.select(userSgShapes, r=True)

Is this approximately right? :curious:


#6

Yes I believe that’s an accurate interpretation :slight_smile: Just to clarify one thing about when you say the “difference” between the user selection and allSgShapes – technically the intersection is giving you the elements common to both sets, whereas “difference” would mean the first set minus matching elements from the second. So in this case, if we’re speaking in set terminology, the “difference” would always be an empty set. But I think you understand what it’s doing correctly.