Sub topic 17
Scripting a Material with Python
Prerequisites and the `bpy` model
This chapter assumes basic Blender navigation, material slots, the Shader Editor, and simple Python syntax. Blender's Python API is called bpy. It lets you create data-blocks, change node inputs, and assign materials without clicking through the interface.
A material is stored in bpy.data.materials. A node-based material has a node tree containing shader nodes and links. The Principled BSDF node combines surface properties, while the Material Output node sends the result to the renderer.
Creating and assigning a Principled material
The following script is safe to run more than once because it reuses a material with the same name. It assigns the material to the active mesh object. If no mesh is active, it creates a cube.
import bpy
material_name = "ScriptedRedPlastic"
# Find or create the material.
mat = bpy.data.materials.get(material_name)
if mat is None:
mat = bpy.data.materials.new(name=material_name)
mat.use_nodes = True
nodes = mat.node_tree.nodes
bsdf = nodes.get("Principled BSDF")
if bsdf is None:
raise RuntimeError("This material has no Principled BSDF node.")
# Values are floats from 0.0 to 1.0.
bsdf.inputs["Base Color"].default_value = (0.8, 0.03, 0.02, 1.0)
bsdf.inputs["Metallic"].default_value = 0.0
bsdf.inputs["Roughness"].default_value = 0.3
bsdf.inputs["IOR"].default_value = 1.45
# Use the active mesh, or create one when necessary.
obj = bpy.context.active_object
if obj is None or obj.type != "MESH":
bpy.ops.mesh.primitive_cube_add()
obj = bpy.context.object
# Add the material only if this object does not already have it.
if obj.data.materials.get(material_name) is None:
obj.data.materials.append(mat)default_value changes an unlinked socket. If an image texture or another node is connected to that socket, the connection supplies the value instead. Socket names can differ between Blender versions, so check the node in the Shader Editor when a script raises a KeyError.
Extending the script
You can create a metallic surface by setting Metallic to 1.0 and lowering or raising Roughness to control reflection sharpness. For glass in Blender 4.0 and later, set Transmission Weight to 1.0, set IOR near 1.45, and use low roughness. A script should also set the material's render-related options when the effect requires them, such as blend settings for some alpha workflows.
Exercise
Which part of the script changes a socket directly, and what happens if another node is linked to that socket?
Show answer
The default_value assignment changes an unlinked socket. A connected node overrides that value.