I' m trying to add some modifiers to an imported .obj file but I have several issues. The code that I' m running is:

import bpy

#Element selection and removal
bpy.ops.object.select_all(action = "SELECT")
bpy.ops.object.delete(use_global = False)

#Model loading
full_path_to_file = "path"
Obj = bpy.ops.import_scene.obj(filepath=full_path_to_file)

def surface_refinement(Render,Vista):
    bpy.ops.object.modifier_add(type = 'SUBSURF')
    bpy.context.object.modifiers["Subdivision"].render_levels = Render
    bpy.context.object.modifiers["Subdivision"].levels = Vista
    #bpy.context.object.modifiers["Subdivision"].quality = 3

Render = 2 
Vista = 1 

The error occurs at bpy.ops.object.modifier_add(type = 'SUBSURF')


Ditch the operators.

Operators return a set indicating the success {FINISHED} or failure {CANCELLED} of an operation.

There a chance that import has imported nothing (and after delete all active object is None) or that the current active object is not a mesh (a "subsurfable" type)

In which case there is no context object and poll will fail.

However test script below ditches all but the import obj operator.

Most importers (check first) select newly created objects ie they are members of context.selected_objects after the operator has run. . Have added note about not adding code for deleting all objects to question code, really not that important either way but could be a bit sticky for a new user tryings it out before realizing. Thank goodness for undo... anyway I digress

How to add modifiers using python script and set parameters?

Using python to set object shading to 'smooth'

Here is test code, adds a subsurf modifier and smooth shading to all newly imported mesh objects.

import bpy

# FWIW Dislike this in question scripts
bpy.ops.object.select_all(action = "SELECT")
bpy.ops.object.delete(use_global = False)
# will deselect instead.

#Model loading
full_path_to_file = "foo.obj"

def surface_refinement(obs, render_levels, view_levels):
    for ob in obs:
        if not ob.type == 'MESH':
        ssm = ob.modifiers.new("SubbyO", type='SUBSURF')
        ssm.render_levels = render_levels
        ssm.levels = view_levels  
        me = ob.data
        me.polygons.foreach_set("use_smooth", (True,) * len(me.polygons))

# test call
render = 2 
view = 1 

surface_refinement(bpy.context.selected_objects, render, view)

This site is temporarily in read only mode and not accepting new answers.

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