a simple one liner!
"""using an object reference""" >>> bpy.context.scene.objects.active = bpy.data.objects["Cube"] # if checked to see which is now active >>> bpy.context.scene.objects.active # this may not update visibly as you might expect in the viewport, # but you will see the origin of active_object, and the name bottom left. bpy.data.objects['Cube']
active != selected, you could have 10 objects selected, of which only 1 can ever be active at a time. Or none selected, but 1 active. To get a better understanding of this not so intuitive situation: unselect everything, if you have two objects in the scene, the last one interacted with will be 'active' (as in, shows the origin, and name displayed bottom left)
Setting the state of an object to 'select = True' , is not the same thing
Setting the state of an object to 'select = True' , is not the same thing
Example usage of active object
as an example, below is code that adds Empties while an object is in Edit Mode, the script must set the active object back to the former object, after an empty is added. Try it with suzanne in Edit Mode, then select one vertex and run the script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# be in edit mode to run this code | |
import bpy | |
from mathutils import Vector | |
myob = bpy.context.active_object | |
bpy.ops.object.mode_set(mode = 'OBJECT') | |
# collect selected verts | |
selected_idx = [i.index for i in myob.data.vertices if i.select] | |
original_object = myob.name | |
for v_index in selected_idx: | |
# get local coordinate, turn into word coordinate | |
vert_coordinate = myob.data.vertices[v_index].co | |
vert_coordinate = myob.matrix_world * vert_coordinate | |
# unselect all | |
for item in bpy.context.selectable_objects: | |
item.select = False | |
# this deals with adding the empty | |
bpy.ops.object.add(type='EMPTY', location=vert_coordinate) | |
mt = bpy.context.active_object | |
mt.location = vert_coordinate | |
mt.empty_draw_size = mt.empty_draw_size / 4 | |
bpy.ops.object.select_all(action='TOGGLE') | |
bpy.ops.object.select_all(action='DESELECT') | |
# set original object to active, selects it, place back into editmode | |
bpy.context.scene.objects.active = myob | |
myob.select = True | |
bpy.ops.object.mode_set(mode = 'EDIT') |