0
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.

Robin Betts
  • 76,260
  • 8
  • 77
  • 190

2 Answers2

3

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"]

...

brockmann
  • 12,613
  • 4
  • 50
  • 93
lemon
  • 60,295
  • 3
  • 66
  • 136
1

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

bpy.context.object.modifiers["Decimate"].ratio = Decimate_Ratio
brockmann
  • 12,613
  • 4
  • 50
  • 93
relaxed
  • 2,267
  • 6
  • 15