Script to select objects by material name

Hi,

I’m trying to select objects by material name via python, so far I have manage to print in the console the objects that has the material name but since my python level is low I don’t know how to select them.

This is what the console prints which is ok:
image

Here is the code:

import bpy

obj_set = set()

for o in bpy.data.objects:
    for m in o.material_slots:
        if "glass" in m.name:
            obj_set.add(o)

print (obj_set)

Cheers,
Juan

1 Like

o.select_set(True)

3 Likes

Hi!

Sorry for hijacking already solved topic, but I was trying to do the same and it always selects only the last object in the scene?

I also have very little experience with Python, so any assistance would be appreciated!

Also, in my case at least, there’s a few materials that were duplicated, resulting in naming some of them “material.002” etc. I would like to select those as well!

import bpy

obj_set = set()

for o in bpy.data.objects:
    for m in o.material_slots:
        if "ffdfsdfsdfs" in m.name:
            obj_set.add(o)
            
o.select_set(True)

Your o.select_set() is outside the loop.

Right, thank you! This worked

Interestingly, there’s one instance where this causes weird things going on. To explain better, here’s what I’m dealing with.

When using this python code and targeting “Texture” (majority of my stock materials are named “Texture-xxyyzz”, it selected correct objects.

BUT, when trying to drag all marked objects, let’s say 20 in this case, for some damn reason, it also moves with them the rest of 40 thousand of other that were intentionally in hidden collections!

Same with copy pasting of those 20 marked objects to a different Blender window/project. Marked 20, but takes another 40k from hidden collection with it!

If anyone would know what’s the problem here, please, let me know. This drives me nuts.

Btw., I tried “bpy.context.view_layer.objects:” instead as someone suggested in Discord, but the result was the same.