Here is a script that checks the material slots of all mesh objects. If there is the word screen in the material's name then it selects the vertices of this material and checks the next material. After the check, the selection is separated into a new object if there were matches.
I think what you were actually looking for are lines 31 and 32:
31: bpy.context.object.active_material_index = idx
32: bpy.ops.object.material_slot_select()
but you also need to select the object to have the correct context (line 21) and do a few other safety checks.
The complete script looks like this:
import bpy
save objects because the operation 'Separate Selection' creates new objects
objects = set(obj for obj in bpy.data.objects)
ensure we are in object mode
if bpy.context.active_object.mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
clear object selection so the context is correct
bpy.ops.object.select_all(action='DESELECT')
for obj in objects:
if obj.type != 'MESH':
print(f"Skipping {obj.name} of type {obj.type}")
continue
print(f"Checking materials of {obj.name} ")
# select object, switch to edit mode & clear vertex selection
bpy.context.view_layer.objects.active = obj
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_all(action='DESELECT')
# check material slots
found = 0
for idx, slot in enumerate(obj.material_slots):
if "screen" in slot.material.name: # <-- materials to look for
print(f"Found material slot #{idx}: {slot.name}")
# select the material slot, then select all vertices with this material
bpy.context.object.active_material_index = idx
bpy.ops.object.material_slot_select()
found += 1
# do 'Separate Selection' if we have a selection from at least one match
if found > 0:
bpy.ops.mesh.separate(type='SELECTED')
# switch back to object mode
bpy.ops.object.editmode_toggle()
Example output for materials with "Blue" in their name:
Checking materials of Cube
Found material slot #1: Ocean Blue
Found material slot #2: Deep Blue
Found material slot #3: Blue Sky
Checking materials of Cylinder
Skipping Camera of type CAMERA
Skipping Light of type LIGHT
Checking materials of Cube default
Checking materials of Sphere
Found material slot #1: Night Blue Sphere
bpy.context.object.active_material_index = idxgood enough to make the material active? It's not really clear what you are trying to achieve. Select Similar > Material has no threshold, and it looks like it only works in Edit mode. A bit more context on what your goal is would help. – Blunder Dec 29 '22 at 16:18bpy.ops.mesh.select_similar(type='MATERIAL', threshold=0.01)selects all faces with the material that the active face in Edit mode has. So why do you need to loop through all material slots and look for a material with "screen" in the name? – Blunder Dec 29 '22 at 16:33bpy.ops.object.material_slot_select()in addition to the...active_material_index = idxfrom the comment above. I'll post a complete script below. – Blunder Dec 31 '22 at 03:07