Search code examples
pythongraphics3dblender

How to set object surface to Background in Blender with Python API


How to set object's material surface to Background in Blender using Python API?

Desired output (UI)

I can only do achieve this in UI:

enter image description here

My code (that doesn't work)

I used this method

obj = ut.import_objects("models/bbox.fbx")[0]  # custom import function
color = (1., 0., 0., 1.)

mat = bpy.data.materials.new("mat")
mat.use_nodes = True
nodes = mat.node_tree.nodes

nodes.clear()
node_background = nodes.new(type='Background')
node_background.inputs[0].default_value = (0,1,0,1)

obj.data.materials.append(mat)

Output

Error: Python: Traceback (most recent call last):
  File "/blender_debug2.py", line 40, in <module>
RuntimeError: Error: Node type Background undefined

What does work

Changing the surface to Principled BSDF does work. But mat.node_tree.nodes does not contain the "Background" key.

def change_color(obj: bpy.types.Object, color):
    mat = bpy.data.materials.new("mat")
    mat.use_nodes = True
    principled = mat.node_tree.nodes['Principled BSDF']
    principled.inputs['Base Color'].default_value = color
    obj.data.materials.append(mat)

Solution

  • It seems like you were on the right track, for nodes you can find the background property within ShaderNodeBackground so the actual code would look more like

    obj = ut.import_objects("models/bbox.fbx")[0]  # custom import function
    color = (1., 0., 0., 1.) # red
    
    mat = bpy.data.materials.new("mat")
    
    mat.use_nodes = True
    
    if mat.node_tree:
        mat.node_tree.links.clear()
        mat.node_tree.nodes.clear()
    
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    
    output = nodes.new(type='ShaderNodeOutputMaterial')
    shader = nodes.new(type='ShaderNodeBackground')
    
    nodes["Background"].inputs[0].default_value = color
    
    links.new(shader.outputs[0], output.inputs[0])
    
    obj.data.materials.append(mat)