TExcelTAD
Home › Assets, Tools & Shipping › Automating Blender with bpy

Automating Blender with bpy

Every manual export is a chance to forget a checkbox. Blender ships a full Python API, bpy, and can run scripts without opening its window, so the whole export step can become one command that CI can run too. You need Python basics; this lesson shows the Blender-specific parts.

Where scripts run

Way Command / place Use for
Scripting workspace Scripting tab → Text Editor → Run Script trying things, one-off fixes
Python console Scripting tab → Console exploring bpy.data interactively
Headless blender --background file.blend --python script.py -- args batch exports, CI
Add-on a module with bl_info/manifest and register() a button artists can click

Turn on Edit → Preferences → Interface → Python Tooltips: hovering a button then shows its Python name (for example bpy.ops.export_scene.gltf), and the Info editor logs every operator you click as Python. That's the fastest way to find an API.

The data model in one minute

python
import bpy

for obj in bpy.data.objects:                 # everything in the file
    print(obj.name, obj.type, tuple(obj.scale))

scene = bpy.context.scene                      # the active scene
print(scene.unit_settings.scale_length)        # 1.0 = metres

mesh = bpy.data.objects["Crate"].data          # an object's mesh data
print(len(mesh.vertices), len(mesh.polygons))
print([m.name for m in mesh.materials])

bpy.data holds the file's data blocks, bpy.context the current selection and mode, and bpy.ops the operators (the same actions as the menus). Operators depend on context (selection, active object, mode), which is why export scripts select objects before calling them.

A batch-export script

This script exports every object in a collection called Export as its own file, for one engine preset, with transforms applied on a temporary copy so the source file is never modified. It is meant to run headless:

python
# export_assets.py
# blender --background art/props.blend --python tools/export_assets.py -- --target unity --out build/assets
import argparse
import os
import sys

import bpy

PRESETS = {
    "unity": ("fbx", dict(apply_scale_options='FBX_SCALE_ALL', axis_forward='-Z', axis_up='Y',
                          bake_space_transform=True, object_types={'MESH', 'ARMATURE'},
                          add_leaf_bones=False)),
    "unreal": ("fbx", dict(apply_scale_options='FBX_SCALE_UNITS', mesh_smooth_type='FACE',
                           object_types={'MESH', 'ARMATURE'}, add_leaf_bones=False)),
    "godot": ("gltf", dict(export_format='GLB', export_yup=True, export_apply=True)),
}

def parse_args():
    argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
    parser = argparse.ArgumentParser()
    parser.add_argument("--target", choices=PRESETS, required=True)
    parser.add_argument("--out", required=True)
    return parser.parse_args(argv)

def export_object(obj, fmt, options, out_dir):
    # Work on a copy so the .blend file keeps its original transforms.
    copy = obj.copy()
    copy.data = obj.data.copy()
    bpy.context.scene.collection.objects.link(copy)
    bpy.ops.object.select_all(action='DESELECT')
    copy.select_set(True)
    bpy.context.view_layer.objects.active = copy
    copy.location = (0.0, 0.0, 0.0)
    bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)

    path = os.path.join(out_dir, obj.name + (".fbx" if fmt == "fbx" else ".glb"))
    if fmt == "fbx":
        bpy.ops.export_scene.fbx(filepath=path, use_selection=True, **options)
    else:
        bpy.ops.export_scene.gltf(filepath=path, use_selection=True, **options)

    mesh = copy.data
    bpy.data.objects.remove(copy, do_unlink=True)
    bpy.data.meshes.remove(mesh)
    return path

def main():
    args = parse_args()
    fmt, options = PRESETS[args.target]
    os.makedirs(args.out, exist_ok=True)
    collection = bpy.data.collections.get("Export")
    if collection is None:
        print("ERROR: no collection named 'Export'")
        sys.exit(1)
    for obj in collection.objects:
        if obj.type != 'MESH':
            continue
        print("exported", export_object(obj, fmt, options, args.out))

main()

Notes on it:

  • Everything after -- on Blender's command line is ignored by Blender and left in sys.argv for your script.
  • sys.exit(1) gives a non-zero exit code, so a CI step fails visibly. Blender returns 0 even if your script raised an exception, unless you also pass --python-exit-code 1; add that flag in CI.
  • transform_apply needs the object selected and active, which is why the script sets both.
  • This version handles meshes only. Rigged characters need their armature exported together and no bake_space_transform; add a separate code path rather than one script with many ifs.

In CI or a Makefile the call looks like this:

bash
blender --background --python-exit-code 1 art/props.blend \
        --python tools/export_assets.py -- --target godot --out game/assets/props

Runnable model: what the script decides

Blender can't run here, but the decisions the script makes (which objects, which file names, what to skip) are plain Python, and that is where most pipeline bugs live. Here they are on a fake scene description:

python · try it yourself
scene = [  # (name, type, collection, scale)
    ("Crate", "MESH", "Export", (1.0, 1.0, 1.0)),
    ("Barrel", "MESH", "Export", (1.0, 1.0, 1.0)),
    ("Lamp Post", "MESH", "Export", (2.0, 2.0, 2.0)),
    ("Key_Light", "LIGHT", "Export", (1.0, 1.0, 1.0)),
    ("Sculpt_HighPoly", "MESH", "WIP", (1.0, 1.0, 1.0)),
]

def safe_name(name):
    return "".join(c if c.isalnum() or c in "-_" else "_" for c in name)

def plan(target):
    ext = ".fbx" if target in ("unity", "unreal") else ".glb"
    for name, kind, collection, scale in scene:
        if collection != "Export":
            continue
        if kind != "MESH":
            print(f"  skip   {name} ({kind})")
            continue
        note = "  (scale applied on copy)" if scale != (1.0, 1.0, 1.0) else ""
        print(f"  export {name} -> {safe_name(name)}{ext}{note}")

for target in ["unity", "godot"]:
    print(target)
    plan(target)
unity
  export Crate -> Crate.fbx
  export Barrel -> Barrel.fbx
  export Lamp Post -> Lamp_Post.fbx  (scale applied on copy)
  skip   Key_Light (LIGHT)
godot
  export Crate -> Crate.glb
  export Barrel -> Barrel.glb
  export Lamp Post -> Lamp_Post.glb  (scale applied on copy)
  skip   Key_Light (LIGHT)

Notice Lamp Post becomes Lamp_Post: spaces in asset names break command lines, URLs and some engine features, so the script normalises them. Better still, reject them in validation (Validating Assets Automatically).

Other jobs worth scripting

  • Rename objects, materials and textures to the project's convention.
  • Generate LODs with a Decimate modifier at fixed ratios and export them as _LOD0…_LOD3.
  • Render thumbnails of every asset for a catalogue or the store page.
  • Bake textures (normal, AO) from high-poly to low-poly for every asset in a folder.
  • Report triangle counts, material counts and texture sizes to a JSON file that CI checks.

Test yourself

How does a script run by blender --background file.blend --python export.py -- --target godot receive --target godot?

  1. Blender parses it
  2. Through sys.argv after the -- separator
  3. From an environment variable
  4. It can't receive arguments

Why add --python-exit-code 1 when running Blender in CI?

  1. To speed it up
  2. So an exception in the script makes Blender exit with a non-zero code and the CI step fails
  3. To enable Python
  4. To print more logs

Why does the export script apply transforms on a copy of the object?

  1. Copies export faster
  2. So the source .blend keeps its original transforms and stays editable
  3. bpy can't modify originals
  4. To create LODs