Store object to variable on creation?

Is there a way to store an object to a variable on creation instead of needing to get it from the scene afterwards?

bpy.ops.object.add(type='EMPTY', radius=1, location=(0.0, 0.0, 0.0))
myEmpty = bpy.context.selected_objects
print(myEmpty[0].name)

not certain what you mean here ?

but after you create a new object it becomes the active object in the scene

happy bl

First of all, like RickyBlender said, you shouldn’t use selected objects to get your newly created object, use this instead:

myEmpty = bpy.context.active_object

But actually that’s not the way I would do it. You should avoid using bpy.ops as much as possible, as it is really slow, and context dependant, and thus can create huge headaches. The good news is that you rarely have a real need to use bpy.ops anyway, and can replace it with direct data operations. For instance, you can create an empty with:

bpy.data.objects.new("ObjectName", None)

And the best part is that this operation returns your object so you can do:

myEmpty = bpy.data.objects.new("ObjectName", None)

The only downside to not using bpy.ops, is that you often have to do more operations to get what you want, as they are more low level, so in the case of adding an object, you have to manually link it to the scene, making your final code something like this:


myEmpty = bpy.data.objects.new("ObjectName", None)
bpy.context.scene.objects.link(myEmpty)
print(myEmpty.name)

1 Like