Sub topic 17
Scripting a material with Python
This chapter assumes you can build a Principled BSDF material by hand in the Shader Editor. It also assumes you can run a script from Blender's Scripting workspace. Basic Python (functions, dictionaries, loops) is enough. The examples target Blender 4.x socket names.
What the script is actually editing
A material is a datablock in bpy.data.materials. Its shader graph lives in material.node_tree, which holds nodes and links. Each node has inputs and outputs, and you reach a socket by name or index. Everything you do in the Shader Editor is a change to one of these three things:
- Create or find a node.
- Set an unconnected input's
default_value. - Add a link between an output socket and an input socket.
Create the material without duplicates
bpy.data.materials.new() always makes a new datablock. If you run the script twice, Blender creates RedPlastic.001 and the old one stays in the file. Look the name up first so the script can be run repeatedly.
Find the Principled node by its type instead of its display name. The type 'BSDF_PRINCIPLED' stays the same when node labels change, and it works even if you renamed the node.
import bpy
def get_principled(mat):
"""Return the Principled BSDF in mat, creating and linking one if missing."""
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
for node in nodes:
if node.type == 'BSDF_PRINCIPLED':
return node
bsdf = nodes.new("ShaderNodeBsdfPrincipled")
output = next((n for n in nodes if n.type == 'OUTPUT_MATERIAL'), None)
if output is None:
output = nodes.new("ShaderNodeOutputMaterial")
links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
return bsdf
def make_material(name, base_color, metallic=0.0, roughness=0.5):
mat = bpy.data.materials.get(name)
if mat is None:
mat = bpy.data.materials.new(name=name)
bsdf = get_principled(mat)
bsdf.inputs["Base Color"].default_value = base_color
bsdf.inputs["Metallic"].default_value = metallic
bsdf.inputs["Roughness"].default_value = roughness
return mat
def assign(obj, mat):
"""Put mat in the object's first slot, adding a slot if there is none."""
if obj.type != 'MESH':
raise TypeError(f"{obj.name} is not a mesh")
if obj.data.materials:
obj.data.materials[0] = mat
else:
obj.data.materials.append(mat)
plastic = make_material("RedPlastic", (0.8, 0.05, 0.05, 1.0), roughness=0.35)
gold = make_material("Gold", (1.0, 0.77, 0.34, 1.0), metallic=1.0, roughness=0.2)
obj = bpy.context.active_object
if obj is not None:
assign(obj, plastic)Two details matter here.
- Color values are four-component RGBA. Passing three numbers to
Base Colorraises an error. - Slots belong to the mesh data by default.
obj.data.materialschanges the mesh, so every object sharing that mesh changes too. To make one object different, set a slot'slinkto'OBJECT':obj.material_slots[0].link = 'OBJECT', then assignobj.material_slots[0].material = mat.
Address sockets by name, and expect renames
bsdf.inputs["Roughness"] is readable, but names changed in Blender 4.0. Old tutorials use Transmission, Subsurface, Emission and Specular. Current versions use these names:
| Effect | Socket name in 4.x | Typical value |
|---|---|---|
| Glass | `Transmission Weight` | 1.0 |
| Skin or wax | `Subsurface Weight` | 0.05 to 0.3 |
| Glow color | `Emission Color` | any RGBA |
| Glow strength | `Emission Strength` | 0 to 10 or more |
| Clear coat | `Coat Weight` | 0 or 1 |
| Highlight strength | `Specular IOR Level` | 0.5 |
A wrong name raises KeyError. When you are unsure, print the real names from your version:
import bpy
mat = bpy.data.materials.new("Probe")
mat.use_nodes = True
bsdf = next(n for n in mat.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')
for socket in bsdf.inputs:
print(socket.name, socket.type)
bpy.data.materials.remove(mat)A few sockets share a name with another, such as the vector inputs on some nodes. For those, index by number (inputs[0]) or loop and check socket.identifier.
Link textures and set color spaces
Setting default_value only works while the socket has no link. Once you link a texture into Base Color, the stored default stays but is ignored. The most common script mistake with images is forgetting the color space. Color maps stay sRGB. Maps that hold data (roughness, metallic, normal) must be Non-Color.
import bpy
def add_image(mat, path, socket_name, non_color=False, location=(-400, 0)):
nodes = mat.node_tree.nodes
links = mat.node_tree.links
bsdf = next(n for n in nodes if n.type == 'BSDF_PRINCIPLED')
tex = nodes.new("ShaderNodeTexImage")
tex.location = location
tex.image = bpy.data.images.load(path, check_existing=True)
if non_color:
tex.image.colorspace_settings.name = "Non-Color"
links.new(tex.outputs["Color"], bsdf.inputs[socket_name])
return tex
mat = bpy.data.materials.get("TexturedMetal") or bpy.data.materials.new("TexturedMetal")
mat.use_nodes = True
bsdf = next(n for n in mat.node_tree.nodes if n.type == 'BSDF_PRINCIPLED')
bsdf.inputs["Metallic"].default_value = 1.0
add_image(mat, "//textures/metal_color.png", "Base Color", location=(-400, 300))
add_image(mat, "//textures/metal_roughness.png", "Roughness",
non_color=True, location=(-400, 0))check_existing=True reuses an image that is already loaded. Without it, each run loads another copy. The // prefix means "relative to the .blend file", so the file must be saved first. A missing file raises RuntimeError from images.load.
A normal map needs a ShaderNodeNormalMap between the texture and the Normal input. Link the texture's Color output to the Normal Map node's Color input, then its Normal output to the BSDF's Normal input.
Settings that live on the material, not the node
Some behavior is a property of the material itself. Alpha is the usual case. The Alpha input on the BSDF does nothing visible until the render method allows blending.
- In Blender 4.2 and later, set
mat.surface_render_method = 'BLENDED'for smooth transparency in Eevee, or'DITHERED'for the faster noisy option. - In older versions, use
mat.blend_method = 'BLEND'.
Cycles ignores both and always honors Alpha. Guard version-specific attributes with hasattr(mat, "surface_render_method") if your script must run on several versions.
Common errors
- `KeyError: 'bpypropcollection[key]: key "Transmission" not found'. You used a pre-4.0 socket name. Print the socket names as shown above.
AttributeError: 'NoneType' object has no attribute 'inputs'.nodes.get("Principled BSDF")returnedNonebecause the node was renamed or deleted. Search by type.- Material appears pink or black after linking an image. The image path did not load, or the wrong color space is set.
- Changes appear in the data but not in the viewport. Call
bpy.context.view_layer.update()or move the mouse over the viewport to redraw. - Numbered duplicates (
.001) pile up. Look up the material by name before creating it.
Exercise
You run a script that calls bpy.data.materials.new("Skin") and sets bsdf.inputs["Subsurface"].default_value = 0.1. It fails with a KeyError on Blender 4.2, and the Outliner shows Skin, Skin.001 and Skin.002 after several runs. Name both fixes.
Show answer
Use the current socket name, Subsurface Weight, because Subsurface was renamed in Blender 4.0. Prevent the duplicates by calling bpy.data.materials.get("Skin") first and calling materials.new only when it returns None.