8

I want to iterate over the faces of a mesh and get the diffuse color of the material that is assigned to the face. How can I get the material that is assigned to the face of the object and the diffuse color of that material?

p2or
  • 15,860
  • 10
  • 83
  • 143
  • 2
    When writing scripts or doing anything with python it's really useful to pull down the info header, do some action and see the command that is logged. In your case here, add a material and you will see bpy.context.object.active_material.diffuse_color, also try searching on the site, chances are someone had this same issue or something similar, ie: https://blender.stackexchange.com/questions/27631/assigning-material-to-every-second-face-via-python. Combining those should help and give you some pointers. – iKlsR May 01 '16 at 22:37

1 Answers1

12
import bpy

context = bpy.context
obj = context.object
mesh = obj.data

for f in mesh.polygons:  # iterate over faces
    print("face", f.index, "material_index", f.material_index)
    slot = obj.material_slots[f.material_index]
    mat = slot.material
    if mat is not None:
        print(mat.name)
        print(mat.diffuse_color)
    else:
        print("No mat in slot", f.material_index)
batFINGER
  • 84,216
  • 10
  • 108
  • 233