Add, remove, clear MaterialSlot of Object by bpy without use bpy.ops?

Hi I hope to make add on to transfer material slot assignment from source to target.
About this case, I only need to transfer about same structure poligons.
(Source object A and Target object B mesh polygon counts and index are same)

I can do it, when Target mesh already have same count material slot, so I plan

  1. remove all material slots from Target Mesh
  2. generate material slots as same as source
  3. set Material_slot from polygon[0] to End.

About 3, I found way… just use loop, then set same material_index for each polygon.

objA.data.polygons[i].material_index = objB.data.polygons[i].material_index

But I can not find way, to clear all Material_slots, and generate new Material_slots…

Hi, You can clear all slots with
obj.data.materials.clear()
To generate new slots you can use append
obj.data.materials.append(bpy.data.materials[‘Any_material’])

1 Like

Thanks!! Materials.clear() worked! I did not think it clear material_slots() ^^;
I already made it, so I will change code without use bpy.ops…

And append worked :smiley:. Then do I need to generate mat first (though I can use source mat)to generate new material_slot?
If there is way to generate empty slot, it seems more useful for me.
because Now I first generate empty slots as same as source. then assign polygons. >> set Materials from saved list. which contain source material. with change name.

Though If there is no other way, I may first append material slot with materials, tthen assign slot for target polygons. anyway thaks, I give up, and had used bpy.ops ^^;

OK, now I change code without bpy.ops, then function work more fast thanks!

hi, do you know if there’s a way to do this for just a single material? materials.clear() removes all materials on the object

you can use obj.data.materials.pop(index = i)