[Bf-python] Activation of the material slots

CoDEmanX codemanx at gmx.de
Sun May 6 21:24:24 CEST 2012


my bad, it should use the current object to set active_material_index 
and needs to set the ob as the scene's active object before calling the 
slot remove operator. Should work for multiple objects now:


import bpy

bpy.ops.object.mode_set(mode='OBJECT', toggle=False)

for ob in bpy.data.objects:
       if ob.type != 'MESH' or not ob.select:
           continue

       mat_slots = {}
       for p in ob.data.polygons:
           mat_slots[p.material_index] = 1

       mat_slots = mat_slots.keys()

       for i in range(len(ob.material_slots)-1, -1, -1):
           if i not in mat_slots:
               ob.active_material_index = i
               bpy.context.scene.objects.active = ob
               bpy.ops.object.material_slot_remove()

Am 03.05.2012 17:56, schrieb Jean Montambeault:
> Le 2012-05-02 18:22, CoDEmanX a écrit :
>> I wrote a small script, which should remove unused materials from
>> material slots of all selected objects:
>>
>> import bpy
>>
>> bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
>>
>> for ob in bpy.context.selected_objects:
>>        if ob.type != 'MESH':
>>            continue
>>
>>        mat_slots = {}
>>        for p in ob.data.polygons:
>>            mat_slots[p.material_index] = 1
>>
>>        mat_slots = mat_slots.keys()
>>
>>        for i in range(len(ob.material_slots)-1, -1, -1):
>>            if i not in mat_slots:
>>                bpy.context.object.active_material_index = i
>>                bpy.ops.object.material_slot_remove()
>>
>> seems to work well...
>>
> Thank you for your answer. :)
>
> Yes it does work very well on one object at a time. For a selection, not
> so well here. Unfortunately I have only three minutes of freedom left
> for now. I'll explore the causes when I'm back in about 10 hours time
> and let you know the results. In any case your script has everything to
> solve the problem for me in the most elegant manner that is afforded to
> us by the API. Yeah!
>
> J.
>
> _______________________________________________
> Bf-python mailing list
> Bf-python at blender.org
> http://lists.blender.org/mailman/listinfo/bf-python



More information about the Bf-python mailing list