I need to make a script that delete duplicated materials (from appending objects) and reassign the materials with the same names to the same material slots. Could you help me figuring out how to do it?

Something like that:

bpy.ops.wm.append (autoselect = True)
    #Check if 'bpy.context.active_object.active_material' has a dot on 4th position from the end (since duplicated material are renamed mat.001)
        #if condition true delete the mat
        #reassign mat with same name minus the 4 last characters of the name string on the same material slot
  • $\begingroup$ Can you check if the object has a material with a given name? $\endgroup$ Oct 10, 2019 at 12:15
  • $\begingroup$ if 'material name' in bpy.context.active_object.active_material.name $\endgroup$
    – globglob
    Oct 10, 2019 at 12:20
  • $\begingroup$ Check this answer: blender.stackexchange.com/a/119258/60759 It delas with textures, materials and even node groups. I haven't tested it thouroughly in 2.80 thoug, but it seems to work fine. $\endgroup$ Oct 10, 2019 at 14:06

1 Answer 1

obj = bpy.context.active_object

for index in range(0, len(obj.material_slots.keys())):   

    obj.active_material_index = index

    if "." in obj.active_material.name:

        mat = obj.active_material.name[:-4]
        obj.data.materials[index] = bpy.data.materials[mat] 

This work, I kind of cheated with the if "."

  • $\begingroup$ But the size of obj.data.materials never changes. There is duplication of material. $\endgroup$ Oct 11, 2019 at 8:19
  • $\begingroup$ This: bpy.data.materials.remove(obj.active_material) delete the material completely from the blend file $\endgroup$
    – globglob
    Oct 11, 2019 at 9:17
  • $\begingroup$ Yes, the size of bpy.data.materials decreases but the size of obj.data.materials is constant. $\endgroup$ Oct 11, 2019 at 9:20
  • $\begingroup$ blender 3.6.2 I cant access obj.data.materials but works with: ` for mat in objOld.material_slots: objNew.material_slots[iMatIndex].material=mat.material; iMatIndex+=1 ` $\endgroup$ Aug 21, 2023 at 18:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .