The answer provided is only partially helpful. Or it is outdated in 2.7
Yes you have to add the nodes (use_nodes = True
). However the default material is the Diffuse BSDF. So if you want to use this, fine, you're done.
But to change the shader being used:
- Remove the shader in place (Diffuse BSDF, otherwise the second element in the
material.node_tree.nodes.values()
list. This is sort of optional, as it can also stay in place, but it's just not tidy and confusing to leave it there.
- Create a new shader node. e.g.
material.node_tree.nodes.new('ShaderNodeEmission')
- Update the link to the
Material Output
node.
material.node_tree.links.new(mat.inputs[0], node.outputs[0])
Here an example I made I use quite often: a Mesh Light
def create_light():
"""
Add a mesh light for cycles
"""
# Add new plane
bpy.ops.mesh.primitive_plane_add(location=(15, -5, 5))
plane = bpy.context.active_object
plane.name = 'Light Plane'
plane.scale = mathutils.Vector((4, 4, 4))
# tilt
plane.rotation_euler.rotate_axis('Y', radians(40))
# Create a new material
material = bpy.data.materials.new(name="Plane Light Emission Shader")
material.use_nodes = True
# Remove default
material.node_tree.nodes.remove(material.node_tree.nodes.get('Diffuse BSDF'))
material_output = material.node_tree.nodes.get('Material Output')
emission = material.node_tree.nodes.new('ShaderNodeEmission')
emission.inputs['Strength'].default_value = 5.0
# link emission shader to material
material.node_tree.links.new(material_output.inputs[0], emission.outputs[0])
# set activer material to your new material
plane.active_material = material