I'm trying to figure out how to change the linked node in a node group on a material via python


enter image description here

I'd like to do the equivalent of picking a new link via here -

enter image description here


Kinda similar to my other answer there.

It's not that trivial because some nodes change their displayed name depending on what they are representing. Group nodes are used to modify node groups but a node group is an actual standalone node tree.

So the green node you are seeing is not actually the node group it represents, but a virtual link to it. You can enter a new interface to modify the sub-node tree it is linked to, by using TAB or clicking on the icon on its top right corner, but they are two different entities.

That being said, you'll need to know your group node's unique identifying name, which is different from its displayed name, which is the sub-node-tree's name.

enter image description here

import bpy

ao = bpy.context.active_object
m = ao.active_material
nodes = m.node_tree.nodes  # Get material nodes
gn = nodes.get("Group")  # Get the group node (Name is case-sensitive)
gn.node_tree = bpy.data.node_groups.get("NodeGroup")  # Change the group node's node tree
  • $\begingroup$ That's awesome, many thanks. I had been circling around querying the node_tree, thinking there would be a list on some property. The notion of get rather than set here would have taken me an age to figure out, if at all. Cheers. $\endgroup$
    – Vertex Ape
    Sep 22 '21 at 16:47
  • 1
    $\begingroup$ Well you can also do bpy.data.node_groups["NodeGroup"] but using get prevents throwing a KeyError exception if the name can't be found. Instead it simply sets the group node's node tree to None $\endgroup$
    – Gorgious
    Sep 23 '21 at 5:45

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.