3

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()
batFINGER
  • 84,216
  • 10
  • 108
  • 233
Cgprojectsfx
  • 31
  • 1
  • 3

1 Answers1

9

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. This appears to be one of the anomalies.
  • Remember to select faces to be unwrapped.

Script

import bpy
from math import radians

context = bpy.context
scene = context.scene
vl = context.view_layer
# deselect all to make sure select one at a time
bpy.ops.object.select_all(action='DESELECT')

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()
        bpy.ops.mesh.select_all(action='SELECT') # for all faces
        bpy.ops.uv.smart_project(angle_limit=66, island_margin = 0.02)
        bpy.ops.object.editmode_toggle()
        obj.select_set(False)

enter image description here Resultant UVMap "LightMap" on Suzanne, using limit angle radians(66) interpreted as 1.152 degrees

Related

https://blender.stackexchange.com/a/172990/15543

batFINGER
  • 84,216
  • 10
  • 108
  • 233
  • I noticed there's now a bpy.ops.uv.lightmap_pack(), it seems to use more of the texture space by allocating rectangles for each face, would this be the better option to use nowadays? – Ray Jan 28 '21 at 20:34