2
$\begingroup$

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:
        s.select_set(False)
    #Select given object.
    obj.select_set(True)
    context.view_layer.update()
    #Run callback.
    callback()
    #Restore selection
    obj.select_set(False)
    for obj in selected_objects:
        obj.select_set(True)
    active_object.select_set(True)

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

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

$\endgroup$
  • 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
2
$\begingroup$

Set the active object with

context.view_layer.objects.active = obj

The active object can be active and unselected.

$\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.