How To Create Mesh Through The Blender Python API

To add custom mesh to the scene through the Blender Python API we need to do the following:

Open the “Text Editor” window.

Import the main Blender Python API module.

Python import bpy
1 importbpy

Any mesh consists of vertices, edges, and faces. Let’s make data blocks for them.

Python vertices = [(0, 0, 0),] edges = [] faces = []
123 vertices=[(0,0,0),]edges=[]faces=[]

Our simple mesh will consist only of a single vertex. So let’s fill only the vertices data block, setting the vertex coordinates.

Next, make the mesh structure with the “new_mesh” name,

Python new_mesh = bpy.data.meshes.new('new_mesh')
1 new_mesh=bpy.data.meshes.new('new_mesh')

and fill it from the data blocks.

Python new_mesh.from_pydata(vertices, edges, faces) new_mesh.update()
12 new_mesh.from_pydata(vertices,edges,faces)new_mesh.update()

We created the mesh, but it couldn’t be added to the scene as raw. Only objects could be added to the scene. Let’s make an object with the “new_object” name and link it with the created mesh.

Python new_object = bpy.data.objects.new('new_object', new_mesh)
1 new_object=bpy.data.objects.new('new_object',new_mesh)

We created the object. But there is more to do. We need a collection in which we will add the created object. Let’s make a new collection with the “new_collection” name and place it into the master scene collection.

Python new_collection = bpy.data.collections.new('new_collection') bpy.context.scene.collection.children.link(new_collection)
12 new_collection=bpy.data.collections.new('new_collection')bpy.context.scene.collection.children.link(new_collection)

Now we can add our object to the scene, placing it into our collection.

Python new_collection.objects.link(new_object)
1 new_collection.objects.link(new_object)

The final code:

Python import bpy # make mesh vertices = [(0, 0, 0),] edges = [] faces = [] new_mesh = bpy.data.meshes.new('new_mesh') new_mesh.from_pydata(vertices, edges, faces) new_mesh.update() # make object from mesh new_object = bpy.data.objects.new('new_object', new_mesh) # make collection new_collection = bpy.data.collections.new('new_collection') bpy.context.scene.collection.children.link(new_collection) # add object to scene collection new_collection.objects.link(new_object)
12345678910111213141516 importbpy # make meshvertices=[(0,0,0),]edges=[]faces=[]new_mesh=bpy.data.meshes.new('new_mesh')new_mesh.from_pydata(vertices,edges,faces)new_mesh.update()# make object from meshnew_object=bpy.data.objects.new('new_object',new_mesh)# make collectionnew_collection=bpy.data.collections.new('new_collection')bpy.context.scene.collection.children.link(new_collection)# add object to scene collectionnew_collection.objects.link(new_object)

After this code execution, by pressing the “Run Script” button, we will add a mesh with a single vertex to the scene.

Tag » How To Add Mesh In Blender