4

I'd like to get all materials using an ambient occlusion (AO) node and return their names in the console:

import bpy

mat = bpy.data.materials for mat in mat: mat_name = (mat.name) ntree = mat.node_tree node = ntree.nodes.get("Ambient Occlusion", None)

if node is not None:
    print("Material With Ambient Occlusion:", mat_name)

It works fine for the start up file, but when I run it in another scene I get this error:

AttributeError: 'NoneType' object has no attribute 'nodes'

What is wrong? And why does the code only work for the start up file?

Peter Mortensen
  • 681
  • 4
  • 11
RodrigoGama
  • 159
  • 5

1 Answers1

5

Not all materials have an associated node_tree. This is only present where the 'use_nodes' checkbox has been used as this creates the node tree.

Your problem is that one or more material does not have a node_tree. The solution is to include a test before the ntree.nodes.get() to first check that there is actually an attribute 'nodes' - and to simply skip that material if none is found:

import bpy

Run through all materials of the current blend file

for mat in bpy.data.materials: # If the material has a node tree if mat.node_tree: # Run through all nodes for node in mat.node_tree.nodes: # If the node type is Ambient Occlusion if node.type == 'AMBIENT_OCCLUSION': # Print the name of the material print("Ambient Occlusion Node found in:", mat.name)

brockmann
  • 12,613
  • 4
  • 50
  • 93
Rich Sedman
  • 44,721
  • 2
  • 105
  • 222