A new material can be created with bpy.data.materials.new()
. You assign a material to a face by setting it's material_index
, which is the material's index from it's location in object.material_slots
, we need to use the length of material_slots
to know the index of the material we just added to the list.
import bpy
obj = bpy.context.object
obj.data.materials.clear()
for f in obj.data.polygons:
m = bpy.data.materials.new('FaceMat' + str(f.index))
# for 2.79 remove the ,1.0 at the end
m.diffuse_color = (0.01*f.index,0.02*f.index,0.03*f.index, 1.0)
obj.data.materials.append(m)
f.material_index = len(obj.data.materials)-1
This is a simple example that sets the diffuse colour used by BI which is also used by cycles for the viewport colour. To create a cycles material you will want to create nodes as well.
You could also do it in two parts, one loop to create materials and another to assign a material based on the material name. This way you could create 10 materials and distribute them across the object.
obj.data.materials.append(bpy.data.materials[mat_name])