# Generating, Selecting, and Unwrapping an Item Added to an Existing Mesh (Python Script)

I've got a script that draws a bunch of individual items onto the same object, and I need to generate a UV map for each item right after it's drawn before moving on to the next one.

My current code seems to me like it should work, because the individual instructions work great when I run them via the console, but when I run them as a script, three of the instructions (bpy.ops.mesh.select_all(action='DESELECT'), bpy.ops.mesh.select_linked(), and bpy.ops.uv.unwrap()) don't seem to do anything.

Can anyone help point out what I am overlooking? Thanks in advance!

Here is a simplified script that can be run on the default cube that basically illustrates what I'm trying to do (it draws a separate plane and tries to unwrap it):

import bpy
import bmesh

obj = bpy.context.object
bm = bmesh.new()
bm.from_mesh(obj.data)

mesh_verts  = bm.verts
mesh_faces  = bm.faces

v1    = mesh_verts.new((2,1,1))
v2    = mesh_verts.new((3,1,1))
v4    = mesh_verts.new((2,2,2))
v3    = mesh_verts.new((3,2,2))

face = mesh_faces.new((v1, v2, v3, v4))

v1    = v4
v2    = v3
v4    = mesh_verts.new((2,3,3))
v3    = mesh_verts.new((3,3,3))

face = mesh_faces.new((v1, v2, v3, v4))

v1    = v4
v2    = v3
v4    = mesh_verts.new((2,4,4))
v3    = mesh_verts.new((3,4,4))

face = mesh_faces.new((v1, v2, v3, v4))

bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(type='VERT')
bpy.ops.mesh.select_all(action='DESELECT')
v4.select_set(True)
bpy.ops.uv.unwrap()
bpy.ops.object.mode_set(mode='OBJECT')

bm.to_mesh(obj.data)


Added geometry to a bmesh is not known by bpy.ops until the call to bm.to_mesh(obj.data).

import bpy
import bmesh

obj = bpy.context.object
# Deselect all first
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')

bm = bmesh.new()
bm.from_mesh(obj.data)

mesh_verts  = bm.verts
mesh_faces  = bm.faces

v1    = mesh_verts.new((2,1,1))
v2    = mesh_verts.new((3,1,1))
v4    = mesh_verts.new((2,2,2))
v3    = mesh_verts.new((3,2,2))

face = mesh_faces.new((v1, v2, v3, v4))

v1    = v4
v2    = v3
v4    = mesh_verts.new((2,3,3))
v3    = mesh_verts.new((3,3,3))

face = mesh_faces.new((v1, v2, v3, v4))

v1    = v4
v2    = v3
v4    = mesh_verts.new((2,4,4))
v3    = mesh_verts.new((3,4,4))

face = mesh_faces.new((v1, v2, v3, v4))

# Select v4
v4.select_set(True)
# Set back bmesh to the mesh
bm.to_mesh(obj.data)

# Unwrap
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(type='VERT')