9
$\begingroup$

Is it possible to check to see if a certain node exists on a material from within Python, for example a diffuse node? I am using Cycles Material Nodes, not Blender Internal or Post-Processing.

$\endgroup$
  • 1
    $\begingroup$ Can you be more specific, do you know the name of the node? is diffuse a name or a type of node? $\endgroup$ – ideasman42 Dec 19 '13 at 15:18
5
$\begingroup$

You can use the bpy_prop_collection.get method which acts like pythons dict.get.

import bpy

mat = bpy.data.materials["MyMaterial"]
if mat.use_nodes:
    ntree = mat.node_tree
    node = ntree.nodes.get("Diffuse BSDF", None)
    if node is not None:
        print("We Found:", node)

This is similar to using:

node = ntree.nodes["Diffuse BSDF"]

However if the node isn't found you'll get an exception.

$\endgroup$
3
$\begingroup$

You can iterate through all the nodes in the node tree and check their properties.

For example, to find if a material node tree contains any diffuse shaders, you could do this:

import bpy

mat = bpy.data.materials['MyMaterial']
# Test if 'Use Nodes' is enabled:
if mat.use_nodes == True:
    nodes = mat.node_tree.nodes
    # Iterate through all the nodes in the node tree and test each one to see if it's a diffuse shader:
    for node in nodes:
        if node.bl_idname == 'ShaderNodeBsdfDiffuse':
            # Do stuff
        else:
            # Do other stuff

You can test any node property (e.g. label, location, name, etc.), to see a full list check the API reference.

$\endgroup$
  • $\begingroup$ I think this can be simplified to: if 'ShaderNodeBsdfDiffuse' in mat.node_tree.nodes:, No need to check every bl_idname. $\endgroup$ – ideasman42 Dec 19 '13 at 14:25
  • $\begingroup$ @ideasman42 I couldn't get that to work.. Maybe that only works for the name attribute? $\endgroup$ – gandalf3 Dec 19 '13 at 18:01
0
$\begingroup$

For example, check if node exists in material nodes by name:

if 'Material Output' in [node.name for node in bpy.data.materials['your_material_name'].node_tree.nodes]:
    print('Yes!')
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.