I want to have a function which deselects currently selected objects, selects a passed object, runs a callback function and then restores the selection. For example in my scene I have two objects Red and Blue. I select the Red object, run this script:

context = bpy.context
data = bpy.data
red = data.objects['Red']
blue = data.objects['Blue']

def select_run_deselect(obj, callback):
    """Selects given obj, runs callback and restores selection"""
    selected_objects = context.selected_objects
    active_object = context.active_object
    #Deselect selected objects.
    for s in selected_objects:
    #Select given object.
    #Run callback.
    #Restore selection
    for obj in selected_objects:

select_run_deselect(blue, lambda: print(context.active_object.name))

and expect the output to be "Blue", but it prints "Red" instead.

  • 2
    $\begingroup$ Set the active object with context.view_layer.objects.active = active_object $\endgroup$ – batFINGER Nov 15 '19 at 14:21
  • $\begingroup$ If you write it in the answer section I'll accept it as the best answer and this question will be closed. Thank you @batFINGER. $\endgroup$ – blablaalb Nov 15 '19 at 14:38

Set the active object with

context.view_layer.objects.active = obj

The active object can be active and unselected.

|improve this answer|||||

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.