2
$\begingroup$

I found this code to remove all unlinked nodes on a material selected , but I want to edit the code to remove all unlinked node in all the material on the scene, I am very bad coding but I know the power of coding, if someone could help me will be great. thanks.

Original code.

import bpy

context = bpy.context
ob = context.object
mat = ob.active_material
#mat = bpy.data.materials.get("Foo") # material Foo
assert (mat is not None and mat.use_nodes), "No material or not node based"
linked_nodes = set()

for link in mat.node_tree.links:
    linked_nodes.add(link.from_node)
    linked_nodes.add(link.to_node)
        
unlinked_nodes = set(mat.node_tree.nodes) - linked_nodes
while unlinked_nodes:
    mat.node_tree.nodes.remove(unlinked_nodes.pop())
$\endgroup$
1

1 Answer 1

3
$\begingroup$

The code you posted will get the current active object and a material from that. So you could make it iterate over all materials in the blend like this.

import bpy

for mat in bpy.data.materials:
    if not mat.node_tree:
        continue  # skip when there is no node tree
    linked_nodes = set()
    for link in mat.node_tree.links:
        linked_nodes.add(link.from_node)
        linked_nodes.add(link.to_node)

    unlinked_nodes = set(mat.node_tree.nodes) - linked_nodes 

    while unlinked_nodes:
        mat.node_tree.nodes.remove(unlinked_nodes.pop())
$\endgroup$
1
  • $\begingroup$ work perfect.... many thanks $\endgroup$ Feb 20 at 17:50

You must log in to answer this question.

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