1
$\begingroup$

I'd like to toggle the Mirror modifier of selected object. I always do weight paint without the Mirror modifier but I have to check the mirrored half part sometimes. This script works fine but it is not so good.

objname = bpy.context.active_object.name
bpy.data.objects[objname].modifiers["User Defined Modifier Name"].show_viewport = not bpy.data.objects[objname].modifiers["User Defined Modifier Name"].show_viewport

This can toggle modifier with modifier name "User Defined Modifier Name" of active object but I need to pre-define modifier name to work it correctly. What I'd like to do is like this. I want to toggle all Mirror modifiers of currently selected objects.

objname = bpy.context.active_object.name
for modifier in bpy.data.objects[objname].modifiers:
    if modifier.type == "MIRROR":
        if modifier == False:
            modifier = True
        else 
            modifier = False

of course it does not work because I need to use this format to disable Mirror modifier.

bpy.data.objects[objname].modifiers["User Defined Modifier Name"].show_viewport

but I don't know how to get modifier name. Do you know how to get modifier name?

$\endgroup$
2
  • 1
    $\begingroup$ Hi and welcome to BSE. If obj = context.object then bpy.data.objects[obj.name] is obj there is really no need to get the name from the object then get the object via the name. $\endgroup$
    – batFINGER
    Commented Sep 9, 2021 at 9:31
  • $\begingroup$ I didn't know it. thank you. $\endgroup$
    – Yokomizo
    Commented Sep 9, 2021 at 17:28

1 Answer 1

2
$\begingroup$

Find mirror modifiers by type.

This will toggle all mirror modifiers of all selected objects

import bpy
from bpy import context

for ob in context.selected_objects:
    mods = getattr(ob, "modifiers", [])
    for m in mods:
        if m.type == 'MIRROR':
            m.show_viewport ^= True

for just the context object, remove the outer loop

ob = context.object
mods = getattr(ob, "modifiers", [])
# .. as above ..

If you only want to change those with a specific name, for example only those with name prefixed with "X"

        if m.type == 'MIRROR' and m.name.startswith("X"):
            m.show_viewport ^= True

If we have a unique and specific name

name = "Bob"
mod = getattr(ob, "modifiers", dict()).get(name)

in which case mod will be the modifier named "Bob" or None if there are no modifiers on this object named "Bob".

Note getattr(ob, property_name, fallback) is used in case an object does not have modifiers. An empty dictionary was used in this case, since it has a get method, as do all blender collections, eg bpy.data.objects.get("Cube") It is rarely the case that objects[name] is used as it will throw a key error if it does not exist.

Consider writing a generic method, and pass modifier type, and one of 'ENABLE', 'DISABLE', 'TOGGLE'

$\endgroup$
2

You must log in to answer this question.

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