Why UV script only works the second run

I have this script:

import bpy

def unwrap_mesh(myObject):
myObject.select = True
bpy.context.scene.objects.active = myObject
# Unwrap
print("unwrap
")
bpy.ops.object.mode_set(mode=‘EDIT’, toggle=False)
bpy.ops.mesh.select_all()
bpy.ops.uv.unwrap()
bpy.ops.object.mode_set(mode = ‘OBJECT’)

obj = bpy.data.objects[2]
unwrap_mesh(obj)

The scene has only one camera, lamp and plane in Blender 2.69.

If i run the script once nothing happends, run again and UV works. I have tested and always works after two runs. Sure must be a reason, but I’m not able to find it.

Any idea?

I have found that adding this, works, but WHY?

def unwrap_mesh(myObject):
myObject.select = True
bpy.context.scene.objects.active = myObject
# Unwrap
print("unwrap
")
bpy.ops.object.mode_set(mode=‘EDIT’, toggle=False)
bpy.ops.mesh.select_all(action = ‘DESELECT’) # <----------------- This line is the difference
bpy.ops.mesh.select_all()
bpy.ops.uv.unwrap()
bpy.ops.object.mode_set(mode = ‘OBJECT’)

obj = bpy.data.objects[2]
unwrap_mesh(obj)

The select_all operator has a default action of “TOGGLE” which will select all the vertices if none is selected or unselect all if at least one vertex is selected. So, by calling select_all(action=‘DESELECT’) you ensure that no vertex is selected, and then by calling select_all() (which is the same as select_all(action=‘TOGGLE’)) you’ll select all you vertices. You can simplify your two lines by simply calling select_all(action=‘SELECT’).

Thanks kevar!

Your explanation clarify my question :slight_smile: