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.
1 |
import bpy |
Any mesh consists of vertices, edges, and faces. Let’s make data blocks for them.
1 2 3 |
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,
1 |
new_mesh = bpy.data.meshes.new('new_mesh') |
and fill it from the data blocks.
1 2 |
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.
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.
1 2 |
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.
1 |
new_collection.objects.link(new_object) |
The final code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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) |
After this code execution, by pressing the “Run Script” button, we will add a mesh with a single vertex to the scene.
1. It will be rightly to sometimes use “print(bpy)”, “print(list(bpy))” or “print(dir(bpy))”.
2. What’s wrong with “bpy.ops.object.add(type=’MESH’)”?
1. You can use the “print” instruction at any time you need to see the required statements.
2. Nothing wrong but operators are sometimes unstable and can require to override the context to be properly executed. If you can, it is better to make your code without system operators.