Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Create A Blender Material With A Python Script

** TL;DR

This Python script makes a basic "Principled BSDF" material in Blender. It takes an array a name for the material and an array of tuples for the settings

Code

import bpy


def create_material(name, params):
    if name not in bpy.data.materials:
        print(f"Making {name}")
        bpy.data.materials.new(name)
        material = bpy.data.materials[name]
        material.use_nodes = True
        for param in params:
            material.node_tree.nodes['Principled BSDF'].inputs[param[0]].default_value = param[1]
    else:
        print(f"Already have {name}")
        
if __name__ == "__main__":
    create_material("BlackSquare", [
        ('Base Color', (0, 0, 0, 1)),
        ('Roughness', 1.0),
    ])
    create_material("WhiteSquare", [
        ('Base Color', (1, 1, 1, 1)),
        ('Roughness', 0.7),
    ])