How to add dynamic paint brushes in Blender 2.8

Hey,
I wanted to ask if there is an alternative to the operator bpy.ops.dpaint.type_toggle(type=‘BRUSH’) to add the brush to the object. The following code is intended to simply apply dynamic paint to a lot of objects, set type to brush and add/toggle the brush. Then set a value to test whether the brush was added correctly and the paint source could set. It works nicely for one object, but for several the behaviour seems erratic. Most of the time it works for one or 2 of the selected obejcts at the first or second try. What am I doing wrong and can improve?

thx in advance

  ` import bpy`
    data = bpy.data
    context = bpy.context
    active = context.active_object

    selobj = context.selected_objects[:]


    def addDynBrush():
        a=0
        for obj in selobj:
            a += 1 
            print("Round " + str(a))
            active = obj
            obj.modifiers.new(name='Dynamic Paint', type='DYNAMIC_PAINT')                       ### add dynamic paint
            obj.modifiers['Dynamic Paint'].ui_type = 'BRUSH'                                    ### change type to brush
            bpy.ops.dpaint.type_toggle(type='BRUSH')                                            ### add/toggle the brush
            #bpy.ops.dpaint.type_toggle(type='BRUSH')                                           ### add/toggle the brush    
            try:
                obj.modifiers['Dynamic Paint'].brush_settings.paint_source = 'VOLUME_DISTANCE'  ####test wheater the brush is there 
            except:
                print("This one didn't work!!!! Objectname = " + str(obj.name))                 ##### result for the console
                bpy.ops.dpaint.type_toggle(type='BRUSH')                                            ### add the brush    again!!!!!
            try:
                obj.modifiers['Dynamic Paint'].brush_settings.paint_source = 'VOLUME_DISTANCE'  ####test wheater the brush is there 
            except:
                print("This one didn't work!!!! Objectname = " + str(obj.name))                 ##### result for the console
              
              
                
    def removeDynBrush(): 
        a = 0 
        
        for obj in selobj:
            a += 1 
            if "Dynamic Paint" in obj.modifiers:
                obj.modifiers.remove(obj.modifiers['Dynamic Paint']) 
    addDynBrush()    # adds Dynamic Paint Brushes   from all selected

    #removeDynBrush() # removes Dynamic  Paint Brushes from all selected    use for reseting your test file while blocking the upper function

Operators that add modifiers usually work on the active object, not selected objects, just like in the user interface. So you need to change the active object each time you call the operator, or override the context for the operator.

This line doesn’t do anything to change the active object:

active = obj

It would be:

context.view_layer.objects.active = obj
1 Like