3
$\begingroup$

I can't quite figure this out, so I am hoping someone can help.

In Python, I want to create an empty object, and add a Cube primitive to the object. After that I want to create a new material, and set the object to use the material.

# Create an empty object.
basic_cube = bpy.data.objects.new("Basic_Cube", None)

# Add the object into the scene.
bpyscene.objects.link(basic_cube)
bpyscene.objects.active = basic_cube
basic_cube.select = True

# Add a Cube primitive to the empty object.
bpy.ops.mesh.primitive_cube_add(location=(0.0, 0.0, 0.0))

basic_cube_mesh.update()

But this does not add the cube primitive to the object. It adds it directly to the scene.

Any suggestions on how to get this to work?

$\endgroup$
  • 1
    $\begingroup$ The Add New Object python script template, in the text editor, creates an operator "Add New Mesh" which adds a cube to the scene, $\endgroup$ – batFINGER Sep 28 '16 at 5:48
3
$\begingroup$

You have to create the object with an empty mesh first, as you cannot assign a mesh to an empty later.

Further: primitive_cube_add(...) is supposed to create an object, since it is the same operator called by Add->Mesh->Cube from the menu.

So you can use BMesh to create your cube later and assign it to the empty mesh:

import bpy
import bmesh

bpyscene = bpy.context.scene

# Create an empty mesh and the object.
mesh = bpy.data.meshes.new('Basic_Cube')
basic_cube = bpy.data.objects.new("Basic_Cube", mesh)

# Add the object into the scene.
bpyscene.objects.link(basic_cube)
bpyscene.objects.active = basic_cube
basic_cube.select = True

# Construct the bmesh cube and assign it to the blender mesh.
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=1.0)
bm.to_mesh(mesh)
bm.free()
$\endgroup$

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.