This may be another simple question but I can't seem to find a straight answer.

I am procedurally generating figures and as part of the last step I want to color the figure red.

If I manually add a new material to the figure I can change the color with bpy.context.object.active_material.diffuse_color = (1, 0, 0)

But I need to automate this step such that the program automatically add a new material and then changes the color. I've tried the following but it doesn't seem to work:

bpy.context.object.active_material.diffuse_color = (1, 0, 0)

It seems the problematic step is adding a new material. Any help would be greatly appreciated.


Actually, I figured it out shortly after posting the question.

Instead of using:


I needed to use:


So the final solution was:

activeObject = bpy.context.active_object #Set active object to variable
mat = bpy.data.materials.new(name="MaterialName") #set new material to variable
activeObject.data.materials.append(mat) #add the material to the object
bpy.context.object.active_material.diffuse_color = (1, 0, 0) #change color
  • 4
    $\begingroup$ Won't always work as obj.active_material will not necessarily be mat $\endgroup$
    – batFINGER
    Jun 28 '16 at 20:33
  • 3
    $\begingroup$ Just use mat.diffuse_color (or bpy.data.materials['Materialname'].diffuse_color) instead. $\endgroup$ Nov 21 '16 at 11:48
  • $\begingroup$ You're a real hero! $\endgroup$ Oct 27 '19 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.