Linking image to UV layer with python?

Hello everyone,

I’ve been using Blender for several years but I’m new to python and programming in general. What I’m trying to do is write a script in Blender to bake the lighting onto all objects in the scene.

Right now the script selects an object, goes into edit mode, creates and names a new UV layer, sets this layer to the active render layer, unwraps the object with the lightmap projection, and creates a new image.

What I can’t figure out how to do is link this image I just created to the active uv layer in order to bake to it. What is the python API call to do this?:spin:

Here’s the code I currently have:

import bpy

s = 1024

#Selects object
ob = bpy.data.objects['Cube']
bpy.context.scene.objects.active=ob
ob
me = bpy.data.meshes['Cube']


#Puts it into edit mode
if bpy.ops.object.mode_set.poll():
    bpy.ops.object.mode_set(mode='EDIT')

#Adds a new UV layer, names it, makes it active render layer
bpy.ops.mesh.uv_texture_add()
lightmap = me.uv_textures.active
lightmap.name = 'lightmap'
me.uv_textures["lightmap"].active_render = True

#Unwraps it
bpy.ops.uv.lightmap_pack(PREF_CONTEXT='ALL_FACES', PREF_PACK_IN_ONE=False, PREF_NEW_UVLAYER=False, PREF_APPLY_IMAGE=False, PREF_BOX_DIV=12, PREF_MARGIN_DIV=0.1)

#Creates new image, names it
bpy.ops.image.new(name="MyLightmap", width=s, height=s, color=(0.0, 0.0, 0.0, 1.0), alpha=True, uv_test_grid=False, float=False)

That’s all I have so far. When I have it working for one object I’ll put it inside a loop so that it will cycle through all the objects.

Any help is appreciated. Also, if anyone has suggestions for improvement or ideas of how to code the rest of it, I’d love to hear. :eyebrowlift:

Thanks in advance,
Tristan