0
$\begingroup$

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)
bm.select_history.add(v4)
bpy.ops.mesh.select_linked()
bpy.ops.uv.unwrap()
bpy.ops.object.mode_set(mode='OBJECT')

bm.to_mesh(obj.data)
$\endgroup$

1 Answer 1

0
$\begingroup$

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')

# Your code...
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))
# ... your code

# 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')
bpy.ops.mesh.select_linked()
bpy.ops.uv.unwrap()
bpy.ops.object.mode_set(mode='OBJECT')
$\endgroup$
1
  • $\begingroup$ Thank you! That did it. $\endgroup$
    – jrban138
    Commented Dec 27, 2020 at 17:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .