5
$\begingroup$

Is it possible to find nodes connected to a node?

For example, could you trace your way back through a node tree from the material output node by finding the node connected to the material output node, then finding the node(s) connected to that node, then the nodes connected to those nodes, etc.?

How is this possible?

$\endgroup$
13
$\begingroup$

The python path to the links between each node is

bpy.data.materials[].node_tree.nodes[].inputs[].links[].from_node

So for each material we want to start at the Material Output node then loop through each array of inputs[] and links[] to move through the connections. Going this way (using from_node) there should only be one link for each input, but if you want to reverse the order (by using to_node) you can have multiple links for each output.

import bpy

def followLinks(node_in):
    for n_inputs in node_in.inputs:
        for node_links in n_inputs.links:
            print("going to " + node_links.from_node.name)
            followLinks(node_links.from_node)

for mat in bpy.data.materials:
    print("Traversing " + mat.name)
    for mat_node in mat.node_tree.nodes:
        if mat_node.type == 'OUTPUT_MATERIAL':
            # we start at the material output node
            print("Starting at " + mat_node.name)
            followLinks(mat_node)
$\endgroup$
  • $\begingroup$ I have thousands of objects for which I need to update their materials' nodes/links using Blender's Python API. I am pretty new to nodes stuff in Cycles and I haven't been able to wrap my head around how I can do that. It seems that some version of your solution here should work for what I want to do. I wonder, could you please take a look at my question here? It would be great if you know how I can do what I want. $\endgroup$ – Amir Mar 8 '18 at 16:39

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.