The mesh me
must not be in edit-mode when writing the bmesh object bm
back to me
- like the error message tells you:
ValueError: to_mesh(): Mesh 'Cube' is in editmode
So, either run the code when the mesh is in object mode, respectively change the mode: bpy.ops.object.mode_set(mode='OBJECT')
Or use a wrapped bm, which means to directly manipulate the editmode mesh through the bmesh module:
import bpy
import bmesh
me = bpy.context.object.data
bm = bmesh.from_edit_mesh(me)
for v in bm.verts:
v.co.x += 1.0
# Update mesh, so we see the changes.
bmesh.update_edit_mesh(me, False, False)
# Because we did not add or remove geometry,
# tessface=False and destructive=False can be used.
# DO NOT DO THIS IF YOU CHANGED GEOMETRY!
# Blender will crash otherwise.
As you see, you can either fill in a mesh, manipulate it (purely in memory, the original mesh is not changed) and write it to a mesh datablock afterwards if desired OR gain access to the editmesh and edit it directly with all changes being applied to the original mesh without copying (the update at the end is required though).
You can chose which way to use based on the current mode to avoid unnecessary mode switches:
import bpy
import bmesh
me = bpy.context.object.data
if me.is_editmode:
bm = bmesh.from_edit_mesh(me)
else:
bm = bmesh.new()
bm.from_mesh(me)
for v in bm.verts:
v.co.x += 1.0
if bm.is_wrapped:
bmesh.update_edit_mesh(me, False, False)
else:
bm.to_mesh(me)
me.update()
BTW: update
is a method of the Mesh type, you need to call it: me.update()