import bpy class MESH_OT_fix_material_names(bpy.types.Operator): """Fixes the material naming, if duplicated are present e.g. Material.001, Material.002 ...""" bl_idname = "mesh.fix_material_names" bl_label = "Fixes the material naming, if duplicated are present" bl_options = {"REGISTER", "UNDO"} def execute(self, context): #Remove all duplicated materials self.merge_duplicated_materials() #Merge material slots for every mesh in the scene #for obj in bpy.context.scene.objects: #if obj.type == "MESH": #self.merge_material_slots(obj) self.report({'INFO'}, 'All duplicated Materials fixed') return {"FINISHED"} def merge_duplicated_materials(self): for material in bpy.data.materials: if material.name[-3].isnumeric(): opti_matName = material.name[:-4] if bpy.data.materials.get(opti_matName): #check if og_mat exists material.user_remap(bpy.data.materials.get(opti_matName)) print("Removed Material: " + material.name) bpy.data.materials.remove(material) else: material.name = opti_matName def merge_material_slots(self, obj): duplicated_material_list = [] #create list with indexes of material slots with the same name for og_slot in obj.material_slots: for slot in obj.material_slots: if slot.name == og_slot.name: if slot.slot_index == og_slot.slot_index: continue if og_slot.slot_index in duplicated_material_list: continue duplicated_material_list.append(int(slot.slot_index)) #delete all material slots within list for slot_index in sorted(duplicated_material_list, reverse=True): obj.data.materials.pop(index = slot_index)