Sub topic 12
Automating the Workflow with Python
Assume that you can navigate Blender, switch between Object Mode and Edit Mode, select mesh components, and create a basic material. This chapter uses Blender’s Python API, which is the set of Python modules that control Blender. The main module is bpy.
Python is useful when you repeat the same UV and material steps across many objects. A script can select the mesh, unwrap it, create a material, load an image, and connect the image to the Principled BSDF shader.
The workflow in code
The script below expects an active mesh object. It uses marked seams if they already exist. If no image exists at the specified path, it creates a generated UV grid instead. This makes the script runnable before you add a final texture.
import bpy
import os
# Get the active mesh object.
obj = bpy.context.active_object
if obj is None or obj.type != "MESH":
raise RuntimeError("Select a mesh object before running this script.")
# Operators such as unwrap need a suitable mode.
if obj.mode != "OBJECT":
bpy.ops.object.mode_set(mode="OBJECT")
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
# Create a UV map if the mesh does not have one.
if obj.data.uv_layers.active is None:
obj.data.uv_layers.new(name="UVMap")
# Select every face and unwrap the mesh.
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.select_all(action="SELECT")
bpy.ops.uv.unwrap(method="ANGLE_BASED", margin=0.001)
bpy.ops.object.mode_set(mode="OBJECT")
# Create or reuse the material.
mat = bpy.data.materials.get("AutomatedTexture")
if mat is None:
mat = bpy.data.materials.new("AutomatedTexture")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
bsdf = nodes.get("Principled BSDF")
if bsdf is None:
bsdf = nodes.new("ShaderNodeBsdfPrincipled")
tex = nodes.get("Image Texture")
if tex is None:
tex = nodes.new("ShaderNodeTexImage")
# Load a file relative to the current .blend file.
image_path = bpy.path.abspath("//textures/brick_color.png")
if os.path.exists(image_path):
image = bpy.data.images.load(image_path, check_existing=True)
image.colorspace_settings.name = "sRGB"
else:
# Use a generated grid while the real image is unavailable.
image = bpy.data.images.get("UVTestGrid")
if image is None:
image = bpy.data.images.new(
"UVTestGrid", width=1024, height=1024
)
image.generated_type = "UV_GRID"
tex.image = image
# Replace any existing Base Color connection.
for link in list(bsdf.inputs["Base Color"].links):
links.remove(link)
links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
# Assign the material to the object.
if len(obj.data.materials) == 0:
obj.data.materials.append(mat)
else:
obj.data.materials[0] = mat
print(f"UV unwrap and material setup completed for {obj.name}")The path beginning with // is relative to the folder containing the .blend file. Change brick_color.png to your image name. The script sets the image to sRGB because it contains visible color. A normal map or roughness map would use Non-Color instead.
What the script does internally
The unwrap operation works on the active UV map. The ANGLE_BASED method tries to preserve angles between connected faces. It can use marked seams to decide where the surface is cut. The script does not create seams automatically, so mark them in Edit Mode first, or add seam-setting code for a known mesh.
The material section creates an Image Texture node and connects its Color output to the Principled BSDF node’s Base Color input. The UV coordinates are then used automatically by the image texture node.
Operators and data access
Blender scripting uses two common styles:
bpy.opscalls an action that resembles a user interface command. Operators often depend on the active object and current mode.bpy.dataaccesses Blender data directly, such as meshes, images, materials, and nodes.
Mode errors are common. For example, mesh selection belongs in Edit Mode, while assigning a material usually works in Object Mode. Set the mode explicitly when a script changes between these operations.
The generated test grid helps you inspect distortion. After running the script, open the Shader Editor and UV Editor. If the grid appears stretched, return to seam placement or adjust the UV islands manually.
Saving image data
Loading an image does not automatically place the image inside the .blend file. Keep the texture in the expected relative folder, or pack it through Blender’s interface with File > External Data > Pack Resources. Save the .blend file after packing. Packing increases the file size, but it prevents a missing external texture when the project moves to another computer.
Exercise
Why does this script set the object to Object Mode before assigning the material, then switch to Edit Mode for unwrapping?
Show answer
Blender operators depend on context. Mesh selection and UV unwrapping require Edit Mode, while reliable material assignment and object data changes are performed in Object Mode.