ofey
ofey

Reputation: 3347

Blender 3.0 with Modifiers in Python

The following script from https://b3d.interplanety.org/en/how-to-apply-modifier-on-selected-objects/ doesn't work. I'm using Blender 3.0 with the Python API. I tried running it with the cube created and with nothing created.

enter image description here

What am I doing wrong?

import bpy
 
for obj in bpy.context.selected_objects:
    bpy.context.view_layer.objects.active = obj
    for modifier in obj.modifiers:
        if modifier.type == 'SUBSURF':
            bpy.ops.object.modifier_apply(
                modifier=modifier.name
            )
            

Thanks any help would be appreciated. Here's the code in the image.

EDITED 24/4/22

You need to select the two vertices of the edge first.

My attempt to select one edge of a default cube and bevel it in python

    import bpy
    import bmesh
    
    obj = bpy.context.active_object  # Get selected object
    
    epsilon = 1e-5  # Threshold to account for floating point precision
    
    if obj:
        bpy.ops.object.mode_set(mode='EDIT')  # Go into edit mode
        bpy.ops.mesh.select_mode(type="EDGE")  # Switch to edge select mode
    
       
        bm = bmesh.from_edit_mesh(obj.data)  # Create bmesh object for easy mesh evaluation
        obj = bpy.context.active_object
        obj.data.polygons[2].select = True
        for e in bm.edges:  # Check all edges
        
            if e.index  == 0:
                print ("abc")
                first_pos = e.verts[0].co  # Get first vert position of this edge
                other_pos = e.verts[1].co  # Get second vert position of this edge
    
                e.select_set(abs(first_pos.x - other_pos.x) <= epsilon and abs(first_pos.y - other_pos.y) <= epsilon)
            
        bmesh.update_edit_mesh(obj.data)  # Update the mesh in edit mode
        bpy.ops.object.modifier_set_active(modifier="Bevel")
        bpy.ops.object.modifier_add(type='BEVEL')
    
        bpy.context.object.modifiers["Bevel"].segments = 10
        bpy.context.object.modifiers["Bevel"].width = 0.37
    

Perhaps I should ask another question.

Blender bevel selected edge of a default cube with python

Upvotes: 0

Views: 2746

Answers (1)

Shaddo
Shaddo

Reputation: 96

Your script is working just fine... Are you sure you did select all your objects before starting the script ?

Maybe you want it to work for all objects in the scene, thus replacing context.selectd_objects by context.scene.objects

Upvotes: 1

Related Questions