# Smart unwrap using script

I am stuck. I am trying to smart unwrap objects individually using script.

I tried this code but it fails. Any help is appreciated

import bpy
import time

for obj in bpy.data.objects:
if (obj.type == 'MESH'):
bpy.context.scene.objects.active = obj
print(obj.name)
bpy.ops.object.editmode_toggle()
bpy.context.object.data.uv_textures['LightMap'].active = True
bpy.ops.uv.smart_project(angle_limit=66, island_margin = 0.02)
bpy.ops.object.editmode_toggle()


Code Edit for 2.8x, for 2.7x see previous revision.

Some Edits

• The collection bpy.data.objects is all objects in a blend file, whether linked to context scene, another scene or no scene. If not in the context scene cannot be the context object. Use scene.objects
• I put the "convenience variable" context in test scripts, so I can paste later into panel or operator code where it is passed as a parameter to most methods, in which case better not to use path addressing from bpy IMO it gets tedious reading bpy.context.object.data.uv_foo.bar.blah
• Add a UV map named "LightMap" if the mesh doesn't already have one.
• Blender uses radians not degrees as the native unit of rotation.

Script

import bpy

context = bpy.context
scene = context.scene
vl = context.view_layer

for obj in scene.objects:
if (obj.type == 'MESH'):
vl.objects.active = obj
obj.select_set(True)
print(obj.name)
lm =  obj.data.uv_layers.get("LightMap")
if not lm:
lm = obj.data.uv_layers.new(name="LightMap")
lm.active = True
bpy.ops.object.editmode_toggle()