12

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.ops.material.new()
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.

switchup621
  • 477
  • 1
  • 5
  • 12
  • creating a new material doesn't apply it to your active object –  Jun 27 '16 at 20:06
  • These are 2 questions asked and both have duplicates: 1: http://blender.stackexchange.com/questions/23433/how-to-assign-a-new-material-to-an-object-in-the-scene-from-python/23434#23434, 2: http://blender.stackexchange.com/questions/23436/control-cycles-material-nodes-and-material-properties-in-python/23446#23446 – Jaroslav Jerryno Novotny Feb 08 '17 at 17:46

1 Answers1

16

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

Instead of using:

bpy.ops.material.new()

I needed to use:

bpy.data.materials.new(name="MaterialName")

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
switchup621
  • 477
  • 1
  • 5
  • 12