Issues with modifiers

Hey all! From time to time I like to write small scripts and add-ons to speed up my workflow. My most recent one is giving me some grief, though, and I’m hoping someone with more Blender/Python experience can help me out.

I wrote a script that adds a solidify and remesh modifier to every selected object. When I run it as a straight python script, everything works beautifully! But when I use the exact same code in the execute() function of an interface button, it loops through the selected objects but adds all of the modifiers to the last object in the bpy.context.selected_objects array only. This is the only code in my script that is causing an issue:


# ...

for obj in bpy.context.selected_objects:
    bpy.context.scene.objects.active = obj
    bpy.ops.object.modifier_add(type='SOLIDIFY')
    bpy.ops.object.modifier_add(type='REMESH')
    bpy.context.object.modifiers["Remesh"].mode='SMOOTH'
    bpy.context.object.modifiers["Remesh"].octree_depth = 7
    bpy.context.object.modifiers["Remesh"].use_smooth_shade = True

return {'FINISHED'}

The only thing I can think of is somehow the add-on code is forcing Blender to lag just far enough so the script loops through the selected objects but doesn’t actually finish adding the modifiers until it’s at the end of the selected_objects array. Any thoughts?

EDIT: I’ve also tried replacing the modifier_add() function with a simpler function, like translate() and that works as expected (each object is moved accordingly). So it seems there’s something with the modifiers themselves that’s causing the issue.

Good news! I discovered the issue: I was executing from the Properties panel, which wasn’t the right context to create the modifiers. So, I moved the button to the UI panel in the 3D viewport, and that immediately fixed the issue.

I would actually avoid operators here and use RNA methods (works indepent of space type):

import bpy

class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"


    def execute(self, context):
        for ob in context.selected_editable_objects:
            if ob.type == 'MESH':
                ob.modifiers.new("", 'SOLIDIFY')
                mod = ob.modifiers.new("", 'REMESH')
                mod.mode = 'SMOOTH'
                mod.octree_depth = 7
                mod.use_smooth_shade = True
        return {'FINISHED'}

Interesting! I’ll definitely change that then. I don’t have a lot of experience with RNA methods.