I am trying to subdivide and finally add a Shrink Wrap modifier to an object using python.

Below is the object SUBDIVIDE code.

import bpy
import bmesh
from bpy.props import IntProperty

class SimpleOperator(bpy.types.Operator):
    bl_idname = "mesh.custom_subdiv"
    bl_label = "Custom Subdiv Mesh Operator"
    bl_options = {'REGISTER', 'UNDO'}
    subd_levels: IntProperty(default=10, options={'HIDDEN', 'SKIP_SAVE'})
    def poll(cls, context):
        return context.active_object.type=='MESH' and context.mode=='OBJECT'

    def execute(self, context):
        ob = context.object
        me = ob.data
        if me.subdiv_prop >= self.subd_levels:
            self.report({'INFO'}, "Maximum reached")
            return {'FINISHED'}
            bm = bmesh.new()
            bmesh.ops.subdivide_edges(bm, edges=bm.edges, cuts=self.subd_levels, use_grid_fill=True)
            self.report({'INFO'}, "{} levels applied".format(self.subd_levels))
            me.subdiv_prop =+ self.subd_levels
            return {'FINISHED'}
def register():
    bpy.types.Mesh.subdiv_prop = IntProperty(default=0)

def unregister():
    del bpy.types.Mesh.subdiv_prop

if __name__ == "__main__":

    # test call

Where do I add the Shrink Wrap code bpy.ops.object.modifier_add(type='SHRINKWRAP') so they can be executed simultaneously?


1 Answer 1


Use the low-level function to add modifiers which allows for direct property access: https://docs.blender.org/api/current/bpy.types.ObjectModifiers.html#bpy.types.ObjectModifiers.new

import bpy

C = bpy.context

# Get the object
obj = C.scene.objects['Cube']

# Add the modifier using the low level function
shrink_mod = obj.modifiers.new(name="Shrinkie", type='SHRINKWRAP')
shrink_mod.offset = 0.01
shrink_mod.target = C.scene.objects['Sphere']

How to add modifiers using python script and set parameters?

If you want to make it work along with my code from your other question How to limit number of times an operator can run in python, add the following lines to the operator:

        # Add the modifier using the low level function
        shrink_mod = context.object.modifiers.new(name="Shrinkie", type='SHRINKWRAP')
        shrink_mod.offset = 0.01
        shrink_mod.target = context.scene.objects['Sphere']

Not the answer you're looking for? Browse other questions tagged .