0
$\begingroup$

In the following script I am trying to create a material on the active object, then change the context to the shader node editor and then delete the existing default node setup:

import bpy

mat = bpy.data.materials.get("Material")
geom = bpy.context.active_object

if mat is None:
    # create material
    mat = bpy.data.materials.new(name="Material")
# Assign it to object
if geom.data.materials:
    # assign to 1st material slot
    geom.data.materials[0] = mat
else:
    # no slots
    geom.data.materials.append(mat)

bpy.context.area.type = 'NODE_EDITOR'
bpy.ops.node.select_all(action='TOGGLE')
bpy.ops.node.delete()

When I first run this script (from the text editor) on my scene I get the following:

RuntimeError: Operator bpy.ops.node.select_all.poll() failed, context is incorrect

Although, curiously, when I run it a second time (again from the text editor), the context is successfully changed to the shader node editor but no nodes are deleted.

And finally, when I run it a third time, it successfully deletes the existing nodes in the shader node editor.

Why does this script apparently work better each time it is run?

(I am using Blender 2.8)

$\endgroup$

1 Answer 1

3
$\begingroup$

To delete the nodes you should override the context of operator bpy.ops.node.select_all. And the reason of error you see is mentioned here.

Actually to delete the nodes, instead of using operator I would use next piece of code:

for node in mat.node_tree.nodes: mat.node_tree.nodes.remove(node)

updated with your part:

import bpy

mat = bpy.data.materials.get("Material")
geom = bpy.context.active_object

if mat is None:
    # create material
    mat = bpy.data.materials.new(name="Material")
# Assign it to object
if geom.data.materials:
    # assign to 1st material slot
    geom.data.materials[0] = mat
else:
    # no slots
    geom.data.materials.append(mat)

# delete nodes
for node in mat.node_tree.nodes:
    mat.node_tree.nodes.remove(node)
$\endgroup$
1
  • $\begingroup$ would have been cool if you also had shown how to do this for the bpy.ops as well so we can learn about how to override context. like for example bpy.ops.node.nw_add_textures_for_principled does not have another way to do it without bpy.ops. $\endgroup$
    – Harry McKenzie
    Commented Jun 22, 2022 at 6:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .