1
$\begingroup$

So I'm having some difficulty with a script I wrote that should loop through a collection of objects and bake the materials for each object. I feel like I'm pretty close, but the script is failing at the bake method.

ex of the data structure:

parent: {
  child1: {
    obj1: {},
    obj2: {}
  },
  child2: {
    obj1: {},
    obj2: {}
  },
}

obj ex of whats being passed into bake:

<bpy_struct, Object("Variant 1") at 0x000001711493E408>

script

variants = bpy.data.collections["Variants"]

def bake(obj):
    print(obj)
    bpy.context.view_layer.objects.active = obj
    image_name = bpy.context.active_object.name + '_BakedTexture'
    image = bpy.data.images.new(image_name,2048,2048)
    nodes = bpy.context.active_object.active_material.node_tree.nodes
    links = bpy.context.active_object.active_material.node_tree.links
    bsdf = nodes.get('default_egg_bsdf')
    texture_node = nodes.new('ShaderNodeTexImage')
    print("1")
      
    texture_node.select = True
    nodes.active = texture_node
    texture_node.image = image #Assign the image to the node
    print("2")    

    bpy.context.view_layer.objects.active = bpy.context.active_object
    bpy.ops.object.bake(type="DIFFUSE")
    print("3")

    links.new(texture_node.outputs[0], bsdf.inputs[0])
    print("4")

def bakeVariants(coll):
    for obj in coll:
        obj = obj.all_objects[1]
        bake(obj)
        
bakeVariants(variants.children)

the error is "Error: No valid selected objects.", I've tried a couple of different methods to set the object being passed in as selected, but none have been working as expected.

If someone could maybe try this script out or provide some feedback on my implementation, I would really appreciate it!

$\endgroup$
1
  • 1
    $\begingroup$ I see where you set the view layer active object but I don't see where you set the bpy.context.active_object. I would guess that's why the bake fails? $\endgroup$ Commented May 14, 2022 at 20:14

1 Answer 1

1
$\begingroup$

to Marty Fouts point, I was not setting the bpy.context.active_object. This was the solution for blender 2.8+ bpy.data.objects[name].select_set(True). I added this to line 3 of my bake script, which resulted in my expected output.

$\endgroup$

You must log in to answer this question.

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