run function when changing object selection

Hi, i want to catch the event of object selection to run a especific funtion.
Everytime i select an object i want to run the function.

Here is the code:

import bpy


def swapCamera():
    context = bpy.context
    scene = context.scene
    currentCameraObj = bpy.data.objects[bpy.context.active_object.name+"_cam"]
    scene.camera = currentCameraObj


class ChangeCameraRig(bpy.types.Operator):
    bl_idname = "rig.change_camera"
    bl_label = "Change Camera Rig"
    
    @classmethod
    def poll(self, context):    
        try:
            ob = context.active_object  
            mode = context.mode     
            name = ob.name
            return ( mode == "POSE" )
        except AttributeError:
            return 0
        
    def execute(self, context):
        swapCamera()
        return {'FINISHED'}
    
    
def register():
    bpy.utils.register_class(ChangeCameraRig)


def unregister():
    bpy.utils.unregister_class(ChangeCameraRig)


if __name__ == "__main__":
    register()
        
       
bpy.ops.rig.change_camera()

Thanks!

It seems you want an Application Handler (bpy.app.handlers.scene_update_post). Adapting the trivial example from the documentation:


def my_handler(scene):
    print("Active object:", scene.objects.active.name)

bpy.app.handlers.scene_update_post.append(my_handler)

This will continuously print the name of the active object in the console, and will change as a new object is clicked on. You can adapt it to your own needs.

Codemanx showed this once in these forums and I was blown away.

You might try to create a “keymap” to activate your operator.
But actually it won’t be a real user input (a keymap), it will be an event based trigger.

Whenever the “Selection” operator runs, it will invoke your operator.
The cool part is that you don’t care about how the selection will occur as long as it runs.