Removing unused materials by using script

Here is simple script to remove unused materials

import bpy

materials = []
objects = []

for mat in bpy.data.materials:
    materials.append(mat)

for obj in bpy.data.objects:
    Object_name = obj.name
    if bpy.data.objects[Object_name].type=='MESH':
        objects.append(Object_name)

for object in objects:    
    for mate in bpy.data.meshes[object].materials:
        if mate in materials:
            materials.remove(mate)

for materil in materials:
    bpy.data.materials.remove(materil)

Any suggestions to improve functionality
This script also delete fake user materials

2 Likes

If it does what it is supposed to do, I don’t see a reason to “improve” the functionality.

Just in case you are not aware of it, variable names can be reused. In the first loop, you are using “mat”, later on “mate” and “materil”. Because all those loops are independent of each other, you could always use the same name. However, doing it like this is still correct!

Thanks for you reply

well this is the the improved script which do not delete the fake user materials

import bpy

materials = []
objects = []
for mat in bpy.data.materials:
    materials.append(mat)
    
for obj in bpy.data.objects:
    Object_name = obj.name
    if bpy.data.objects[Object_name].type=='MESH':
        objects.append(Object_name)
for object in objects:    
    for mate in bpy.data.meshes[object].materials:
        if mate in materials:
            materials.remove(mate)
for materil in materials:
    if bpy.data.materials[materil.name].use_fake_user==True:
        materials.remove(materil)
    else:
        bpy.data.materials.remove(materil)