In Blender 2.80 onward:
import bpy
mesh = bpy.data.meshes.new("myBeautifulMesh") # add the new mesh
obj = bpy.data.objects.new(mesh.name, mesh)
col = bpy.data.collections["Collection"]
col.objects.link(obj)
bpy.context.view_layer.objects.active = obj
verts = [( 1.0, 1.0, 0.0),
( 1.0, -1.0, 0.0),
(-1.0, -1.0, 0.0),
(-1.0, 1.0, 0.0),
] # 4 verts made with XYZ coords
edges = []
faces = [[0, 1, 2, 3]]
mesh.from_pydata(verts, edges, faces)
We can make a function, too.
import bpy
def add_mesh(name, verts, faces, edges=None, col_name="Collection"):
if edges is None:
edges = []
mesh = bpy.data.meshes.new(name)
obj = bpy.data.objects.new(mesh.name, mesh)
col = bpy.data.collections[col_name]
col.objects.link(obj)
bpy.context.view_layer.objects.active = obj
mesh.from_pydata(verts, edges, faces)
verts = [( 1.0, 1.0, 0.0),
( 1.0, -1.0, 0.0),
(-1.0, -1.0, 0.0),
(-1.0, 1.0, 0.0),
]
faces = [[0, 1, 2, 3]]
add_mesh("myBeautifulMesh_1", verts, faces)
verts = [( 3.0, 1.0, 0.0),
( 3.0, -1.0, 0.0),
( 2.0, -1.0, 0.0),
( 2.0, 1.0, 0.0),
]
add_mesh("myBeautifulMesh_2", verts, faces)