0
$\begingroup$

I'm looking to expand on my question that was answered here: Print to Info.

How to prompt a user when an operator is performed under the wrong context. Let's say you need to have a mesh object selected when performing a certain operator, but you have a camera or light selected instead. Typically you'll get a Traceback error if you don't have the right type of object selected. What I would like, instead, is to be able to prompt the user to "Please Select a Camera", or "Please select a Mesh", etc., if they don't already have the proper object selected, thus avoiding the error message. This is also needed if the user is in Object Mode when they need to be in Edit Mode.

I've tried this for the Mesh and in Edit mode example, but it's not working. It would need to both print a message if nothing is selected, print if the wrong context is selected (say a camera or light), and print if the user is not in Edit mode.

EDIT: I adjusted the code. This now grey's out the button when no object is selected. It also drops the user from Object into Edit mode when a mesh is selected. Not exactly what I was going for, but somewhat better:

@classmethod
def poll(cls, context):
    active_object = bpy.context.view_layer.objects.active
    return active_object is not None and active_object.type == 'MESH' and (context.mode == 'EDIT_MESH' or active_object.select_get())


def execute(self, context):
    for obj in bpy.context.selected_objects:
        bpy.ops.object.mode_set(mode='EDIT')

    active_object = bpy.context.view_layer.objects.active
    if active_object is not None: self.report({'INFO'}, "Extrude")
    
    else: self.report({'INFO'}, "Please Select a Mesh!")

Old Code looked like this:

@classmethod
def poll(cls, context):
    return active_object is not None and active_object.type == 'MESH' and 
(context.mode == 'EDIT_MESH' or active_object.select_get())

def execute(self, context):
    if bpy.context.view_layer.objects.active: print("Extrude", bpy.context.view_layer.objects.active.name)   

    else: print("Please Select a Mesh")

enter image description here

$\endgroup$
2

0

You must log in to answer this question.

Browse other questions tagged .