1

I encounter the following problem. If, somewhere in my script, I switch from Object mode to Edit Mode and back, the indices of the elements in my object become messed up.

To recreate the problem: Create a cube (or any mesh object for that matter) and run the following Python snippet:

import bpy

object = bpy.context.active_object

for v in object.data.vertices:
    print('1',v.index)
    bpy.ops.object.mode_set(mode = 'EDIT')
    bpy.ops.object.mode_set(mode = 'OBJECT')
    print('2',v.index)

I expect the following output:

1 0
2 0
1 1
2 1
1 2
2 2
1 3
2 3
1 4
2 4
1 5
2 5
1 6
2 6
1 7
2 7
1 8
2 8

However, I end up with the following output (the numbers change seemingly randomly everytime I run the script):

1 0
2 123
1 124
2 -166
1 -165
2 116
1 117
2 -164
1 -163
2 153
1 154
2 -162
1 -161
2 182
1 183
2 -160

Does anyone know what causes this problem and how to solve/workaround this? I prefer NOT to use the BMesh module, since the bpy operators suit my needs much better.

Thanks in advance,

Niels

Niels
  • 324
  • 1
  • 8
  • Can only manipulate mesh data (eg me.vertices) in object mode. eg to set a vert to selected in object mode v.select = True then flip into edit mode it's selected. Setting it in edit mode does nada. Blender makes a (lets call it a) copy and places in edit mode and writes it back when toggling back to object mode. Hence a reference to a vertex before and after will not work as expected. It would be the same case with bmesh. An object mode bmesh wont pick up any changes if done (after loading) to the mesh in edit mode and an edit mode one will be dead after the toggle. This may be a – batFINGER Mar 31 '20 at 12:56
  • far more answerable question if you describe what you are intending to do that requires having a vert reference in object mode to use after a toggle. If a vert is deleted in edit mode above, the code would quite likely crash blender. – batFINGER Mar 31 '20 at 12:59
  • Thanks for your answer batFINGER. What I intend to do is calculate a gradient for each vertex. So in pseudocode, it would look like this: – Niels Mar 31 '20 at 13:09
  • For every vertex in object
  • 1a) Select this vertex (v.select = True) 1b) Select neighbor vertices (bpy.ops.mesh.select_more()) 1c) Store normal angles 2) Compare normal angles within selection... etc.

    For being able to perform a bpy operator (select_more() in this case) I need to toggle to Edit Mode. While (as you said) for manipulating mesh I need to be in Object Mode. So I constantly need to toggle, right?

    – Niels Mar 31 '20 at 13:25