9
$\begingroup$

I would like to create a mesh, then interactively add vertices (afterwards, possibly through a loop) to it through python.

Is that possible?

I can't find enough info from other answers to really get this going - either I find out how to create a mesh, or how to add a vertex, but can't seem to put them together in to a script.

$\endgroup$
  • $\begingroup$ Nowadays you'll want to use bmesh...I don't have time to write a full answer, but I will later if no one else has. $\endgroup$ – JakeD Aug 29 '16 at 12:32
  • 3
    $\begingroup$ related: blender.stackexchange.com/questions/414/… $\endgroup$ – zeffii Aug 29 '16 at 12:42
  • 1
    $\begingroup$ related: blender.stackexchange.com/questions/2407/… $\endgroup$ – zeffii Aug 29 '16 at 12:44
  • 2
    $\begingroup$ if those two links aren't helpful, please your edit question to include more details about what exactly you don't understand. $\endgroup$ – zeffii Aug 29 '16 at 12:45
14
$\begingroup$

This is how to create a new object and add the vertices in the verts list:

import bpy
import bmesh

verts = [(1, 1, 1), (0, 0, 0)]  # 2 verts made with XYZ coords
mesh = bpy.data.meshes.new("mesh")  # add a new mesh
obj = bpy.data.objects.new("MyObject", mesh)  # add a new object using the mesh

scene = bpy.context.scene
scene.objects.link(obj)  # put the object into the scene (link)
scene.objects.active = obj  # set as the active object in the scene
obj.select = True  # select object

mesh = bpy.context.object.data
bm = bmesh.new()

for v in verts:
    bm.verts.new(v)  # add a new vert

# make the bmesh the object's mesh
bm.to_mesh(mesh)  
bm.free()  # always do this when finished

This is how to alter an existing mesh:

import bpy
import bmesh

verts = [(1, 1, 1), (0, 0, 0)]  # 2 verts made with XYZ coords
mesh = bpy.context.object.data
bm = bmesh.new()

# convert the current mesh to a bmesh (must be in edit mode)
bpy.ops.object.mode_set(mode='EDIT')
bm.from_mesh(mesh)
bpy.ops.object.mode_set(mode='OBJECT')  # return to object mode

for v in verts:
    bm.verts.new(v)  # add a new vert

# make the bmesh the object's mesh
bm.to_mesh(mesh)  
bm.free()  # always do this when finished
$\endgroup$
  • $\begingroup$ thanks a great deal for this, pycoder - much appreciated. $\endgroup$ – Jono Sep 4 '16 at 9:21
  • $\begingroup$ @Jono: pycoder? $\endgroup$ – HelloGoodbye Sep 4 '18 at 12:04
  • 1
    $\begingroup$ @HelloGoodbye I used to be pycoder...changed my name when I started joining more SE websites. You'll see this kind of references all over the sites since there is no good renaming system. $\endgroup$ – JakeD Sep 4 '18 at 16:02
  • $\begingroup$ This no longer works in Blender 2.80 $\endgroup$ – Ron Jensen Aug 7 at 21:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.