I have difficulties trying to select a bunch of object by part of their materialname. eg. i've got some objects and 2 of them have a material that contains the word "text". In the end I want to parent these object to an empty and then move them to a hidden layer.

i've tried the following code, but this gives errors.

textmat = [mat for mat in bpy.data.materials if fnmatch.fnmatchcase(mat.material, "*text*")]

obj = bpy.data.objects
for ob in obj:
    if ob.type == 'MESH':
        for m in ob.material_slots:
            if m.material == textmat:
                ob.select = False

i'm obviously doing something wrong, but my python skills are still limited



In that case, even a simple condition should do the trick.

import bpy

obj_list = []

for o in bpy.data.objects:
    for m in o.material_slots:
        if "text" in m.name:

print (obj_list)

I suggest add the items to a set instead of a list — avoids adding multiple entries of identical objects (in case there are multiple materials per object containing text as substring in their name).

import bpy

obj_set = set()

for o in bpy.data.objects:
    for m in o.material_slots:
        if "test" in m.name:

if len(obj_set):
    bpy.ops.object.add(type='EMPTY', location=(0,0,0))
    emtpy_obj = bpy.context.object
    for o in obj_set:
        o.parent = emtpy_obj
  • $\begingroup$ Perhaps append o , if len([m for m in o.material_slots if "text" in m.name]) to avoid multiples. $\endgroup$ – batFINGER Aug 15 '17 at 12:48
  • $\begingroup$ Yep, might be a good thing. I also thought about creating a set instead of a list to keep it clean. Let's wait for the OP... Thank you @batFINGER $\endgroup$ – brockmann Aug 15 '17 at 12:57
  • $\begingroup$ thanks, both work. Which one would you recommend and what's the exact difference.. $\endgroup$ – Andre Bredeweg Aug 15 '17 at 13:06
  • $\begingroup$ @AndreBredeweg What do you mean? Set vs. list? $\endgroup$ – brockmann Aug 15 '17 at 13:11
  • $\begingroup$ Yes indeed, a set vs list. $\endgroup$ – Andre Bredeweg Aug 15 '17 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.