2

I am trying to write a little script that checks if mesh has more than one material, and if it does, remove materials until there is only one left on the item. Here is what I have so far:

import bpy
for ob in bpy.data.objects:
    number_of_mats = len(ob.material_slots.items())
    if number_of_mats > 1:
        for i in range(number_of_mats-1):
            # remove material here?

I cannot seem to figure out the method to remove a mat at this point. Any suggestions?

brockmann
  • 12,613
  • 4
  • 50
  • 93
aaron
  • 345
  • 1
  • 10

3 Answers3

2

You can set the index of the list to 1, iterate through the upcoming slots, call and override the context of material_slot_remove(). Demo on how to remove all slots > 0:

Blender 3.2+

import bpy
from bpy import context

for obj in context.selected_editable_objects: obj.active_material_index = 1 for i in range(1, len(obj.material_slots)): with context.temp_override(object=obj): bpy.ops.object.material_slot_remove()

Blender 2.8+

import bpy

for obj in bpy.context.selected_editable_objects: obj.active_material_index = 1 for i in range(1, len(obj.material_slots)): bpy.ops.object.material_slot_remove({'object': obj})

p2or
  • 15,860
  • 10
  • 83
  • 143
brockmann
  • 12,613
  • 4
  • 50
  • 93
1

You can also do it without operators

import bpy
for ob in bpy.data.objects:
    # Skip things without materials (armatures, etc.)
    if not hasattr(ob.data, 'materials'):
        continue
while len(ob.data.materials) > 1:
    ob.data.materials.pop()

scurest
  • 10,349
  • 13
  • 31
0

When I remove a material in the ui, this is echo'd:

bpy.context.object.active_material_index = 2
bpy.ops.object.material_slot_remove()

Looks like the documentation live here.

Hope that helps, Koen

Koen
  • 13
  • 3