15
$\begingroup$

From my python script I want to add some objects to scene and process them later (add constraints etc.). If the object to be added is an Empty, I can simply write:

>>> name = "MyObject"
>>> obj = bpy.data.objects.new(name, None)
...
>>> process(obj)

However if the object to be added is a simple mesh, we may use bpy.ops.mesh.primitive_* operators, which adds objects (e.g. cube) to the scene.

>>> bpy.ops.mesh.primitive_cube_add(radius=2)

But how can I get reference to the newly added object? It returns {'FINISHED'} instead of the reference to object.

>>> obj = ??? 
>>> process(obj)

We do not know name of the new object (and I'm not interested in guessing it:)). Instead, I've tried using the index, but it did not work (gives wrong result):

>>> obj = bpy.data.objects[-1] # We don't know the name :(
bpy.data.objects['Lamp']
>>> # ^^ bpy.data.objects['Cube'] was expected
$\endgroup$
1
  • $\begingroup$ Thank you for bpy.data.objects.new(name, None), that is a cool trick for Empty creation. $\endgroup$ Commented Mar 8, 2021 at 12:24

1 Answer 1

15
$\begingroup$

Objects constructed with bpy.ops.mesh.primitive_* are automatically active. If there's no selection-changing operations immediately after object creation, you can access it through bpy.context.active_object or bpy.context.object.

$\endgroup$
1
  • $\begingroup$ Note that only one object can be active. If an operator creates multiple objects, it will likely select the new ones, and maybe make one active (but not necessarily, especially true for importers). A previous selection may or may not be cleared, so better compare selection states before/after to find all new or updated objects. $\endgroup$
    – CodeManX
    Commented Feb 15, 2014 at 0:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .