Create Texture Node inside Material

Hey Guys,

I am trying to write my first script in Blender.
In essence what I want to do is, Bake a single AO Image for all selected Objects.

So far I managed to create a new Image and a new Material to and apply the Image to all selected objects.
Where I struggle is, creating an Image Texture Node inside the Material.
But as far as I understand, I need to have this Node Selected and the image applied to have Cycles bake to the correct Image map.

The error we get bpy_prop_collection has no attribute add_node

So far this is what I have got:

Thanks so much for any help!

import bpy

VARIABLES

ao_image_name = “AO_Channel”

object_selection = bpy.context.selected_objects
#object_selection = bpy.ops.object.select_all(action=‘SELECT’)
print(object_selection)

if not ao_image_name in bpy.data.images:
ao_image = bpy.ops.image.new(name=“AO_Channel”, width=4096, height=4096, color=(0.0, 0.0, 0.0, 1.0), alpha=True, generated_type=‘BLANK’, float=False, use_stereo_3d=False)

mat_ao = bpy.data.materials.get(“mat_AO”)

Create Material and Map

if mat_ao is None:
mat_ao = bpy.data.materials.new(name=“mat_AO”)

mat_ao.use_nodes=True
node_tree = bpy.data.materials[‘mat_AO’].node_tree
node_tree.nodes.add_node(“ShaderNodeTexImage”)
ao_texture_node = mat_ao.node_tree.nodes.add_node(“ShaderNodeTexImage”)

ao_texture_node.image = ao_image

The node_tree.nodes doesn’t have a add_node function… just a new():

[...]
node_tree = bpy.data.materials['mat_AO'].node_tree
ao_texture_node = node_tree.nodes.new('ShaderNodeTexImage')
ao_texture_node.image = ao_image
1 Like

Awesome! Thank you.
Sorry to bother you with such nonsense, but I ran into a felt brickwall there…