I am writing an addon that displays the mesh modifiers in a listbox, with the settings below the box.
The issue I have is with the active index for the listbox - I'm using a custom property because there is no internal 'active' property for modifiers. The problem I have is that when the last modifier is removed, the index reaches true zero (index size zero), and I get a panel crash plus a console message:
IndexError: bpy_prop_collection[index]:index 0 out of range, size 0
If I then re-add a modifier, the problem resolves and the panel(listbox) reappears.
How can I structure this so the listbox doesn't crash when the index reaches size 0? Here's the backbone of the script:
import bpy
bpy.types.Object.modifier_active_index = bpy.props.IntProperty()
def draw(self, context):
layout = self.layout
global num
global atype
global aname
global amod
num = bpy.context.object.modifier_active_index
ob = context.object
obname = context.object.name
amod = bpy.data.objects[obname].modifiers[num]
amods = bpy.data.objects[obname].modifiers
atype = bpy.data.objects[obname].modifiers[num].type
aname = bpy.data.objects[obname].modifiers[num].name
rows = 2
row = layout.row()
row.template_list("UI_UL_list", "", ob, "modifiers", ob, "modifier_active_index", rows=rows)
Edit:
class OBJECT_OT_modifier_move(bpy.types.Operator): #move active modifier down in stack
bl_idname = "object.modifier_action"
bl_label = "Modifier Action"
action = bpy.props.EnumProperty(
items=(
('UP', "Up", ""),
('DOWN', "Down", ""),
('REMOVE', "Remove", ""),
('ADD', "Add","")
)
)
def invoke(self, context, event):
ob = context.object
idx = ob.modifier_active_index
if self.action == 'ADD':
if bpy.ops.object.modifier_add(type = '') == {'FINISHED'}: #how do I call the menu with modifier.type enums
ob.modifier_active_index = len(ob.modifiers) - 1
try:
mod = ob.modifiers[idx]
except IndexError:
pass
else:
if self.action == 'DOWN' and idx < len(ob.modifiers) - 1:
if bpy.ops.object.modifier_move_down(modifier=mod.name) == {'FINISHED'}:
ob.modifier_active_index += 1
elif self.action == 'UP' and idx >= 1:
if bpy.ops.object.modifier_move_up(modifier=mod.name) == {'FINISHED'}:
ob.modifier_active_index -= 1
elif self.action == 'REMOVE':
bpy.ops.object.modifier_remove(modifier=mod.name)
if idx >= 1:
ob.modifier_active_index -= 1
return {"FINISHED"}