What is under the mouse cursor?

I need an operator that tells me what object is under the cursor. As far as I know there is no such operator out of the box, so I have tried to build my own using bpy.ops.view3d.select(). The problem (I think) is that this operator only have the invoke method implemented. Is there a way to explicitly call the invoke method of an operator?

Here is roughly what I have tried:

class MyCode(bpy.types.Operator):
    bl_idname = "object.my_code"
    bl_label = "My Code"
    bl_options = {'UNDO'}

    def invoke(self, context, event):
        selectedObjs = bpy.context.selected_objects
        for obj in selectedObjs:
            obj.select = False
        bpy.ops.view3d.select() # fails since it tries to call the non existing execute method
        if bpy.context.selected_objects:
            # do my stuff here

        #restore things
        for obj in selectedObjs:
            obj.select = True
        return {'FINISHED'}

But then I get:

wm_operator_invoke: invalid operator call 'VIEW3D_OT_select'

Workaround anyone?

I think what you need to do here is get the cursor x, y position and shoot a ray into the viewport to see what it hits…somehow.

Other addons do it I’m sure so just needs a little searching to figure it out.

go to Text editor, Templates > Python > Operator Modal View3D Raycast for a ray cast example

Thanks, will have a look at it this weekend :slight_smile: