0
$\begingroup$
bpy.context.view_layer.objects.active = bpy.data.collections['Collection'].objects[f"{x.name}"]
bpy.ops.object.modifier_add(type = "DECIMATE")
                
bpy.context.object.modifier["Decimate"].ratio = Decimate_Ratio

Decimate_Ratio is just a math equation

I've tested the code alone without putting it in a function, but now I'm required to apply it to an addon and put it in a function and all the sudden the error appears.

$\endgroup$
0

2 Answers 2

3
$\begingroup$

Except for the 's' that is missing in your code, you should avoid using bpy.ops for that.

Use for example something like this instead:

import bpy

obj = bpy.data.collections['Collection'].objects['Cube']

decimate = obj.new(name='Decimate', type='DECIMATE')

decimate.ratio = 0.5

The reasons are: bpy.ops is slower (it will cause GUI updates, etc.) and most importantly you can't have a guaranty to access the modifier by its name like bpy.context.object.modifiers["Decimate"] as Blender will name it differently in case of name conflicts (Decimate, Decimate.001, Decimate.002, ...). ObjectModifiers.new() on the other hand, adds new modifier and returns a reference to the newly added modifier:

>>> C.object.modifiers.new('Decimate', 'DECIMATE')
bpy.data.objects['Cube'].modifiers["Decimate"]

>>> C.object.modifiers.new('Decimate', 'DECIMATE')
bpy.data.objects['Cube'].modifiers["Decimate.001"]

...
$\endgroup$
1
$\begingroup$

Try object.modifiers[] with s in third line:

bpy.context.object.modifiers["Decimate"].ratio = Decimate_Ratio
$\endgroup$

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