# Same faces for different objects

I am new to Blender. I have 2 objects (e.g 2 box mesh) I would like to export their properties as obj file using python scripting. I would like to export the vertex of both objects firstly, followed by their faces. This is the code I am using below

import bpy

obj = list(bpy.data.objects)

print("Cube\n")
for a in obj:
mesh =a.data
for v in mesh.vertices:
#random output compared to what we have in the original file
print("v %.4f %.4f %.4f\n" % v.co[:]) #x,y,z coordinates

print("\n # 8 vertices\n")
for a in obj:
mesh =a.data

print( "g " +a.name+ "\n")
for p in mesh.polygons:
print("f")
for i in p.vertices:
print(" %d" % (i + 1))
print( "\n")
OUTPUT
g.cube 1

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

g Cube.002

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


Both faces of both objects are the same. This is not what I want. I would like the faces of the second object to start from 9 and so on.

• Each mesh has its own face indexation, meaning it will only contain indices between 0 and its number of vertices -1 (NOT guaranteed though because a mesh can contain vertices which are not linked to a face). If you want to add to that, you can use a global counter before the for a in obj: loop, which will be incremented after by len(mesh.vertices) for each successive object. As I said you might skip some vertices, but not knowing more about your end goal it's hard to give more precise information Jul 18, 2021 at 21:19
• You might save time to base your code in the original OBJ exporter as it is written in python. Jul 18, 2021 at 23:49

Make a joined bmesh.

At the risk of not re-inventing the wheel, since blender ships with an OBJ exporter

As shown in [find link re joining bmeshes] can read multiple meshes into one bmesh.

• Update normals after reading mesh to update indices. Possibly other ways to do this.

• Increment the edge count.

Test script.

import bpy
import bmesh

context = bpy.context

bm = bmesh.new()
bm.verts.new() # since you are indexing from 1
index = 0
for ob in context.selected_objects:

if not ob.type == 'MESH':
continue
print()
print(f"o {ob.name}")
print()
bm.from_mesh(ob.data)
# use normal update to force re-index
bm.normal_update()
for f in bm.faces[index:]:
print(f"f {' '.join(str(v.index) for v in f.verts)}")
index += len(bm.faces)


Test output.

o Cube

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

o Cube.001

f 9 10 11 12
f 13 16 15 14
f 9 13 14 10
f 10 14 15 11
f 11 15 16 12
f 13 9 12 16


Ultimately would join them all into one bmesh, call the normal update once. Use meshes geom counts to slice.