How can I make a condition for every time a new object is added to the scene? Example: Every time an object is added, it's given a triangulate modifier?
-
1You can monitor the dependency graph with a handler, and every time it is updated compare an old list of objects to the current list of objects and if a new one is found add your modifier to it. – Psyonic Dec 26 '22 at 22:58
1 Answers
As @Psyonic has mentioned: You can monitor the dependency graph with a handler, and every time it is updated compare an old list of objects to the current list of objects. And if a new one is found add your modifier to it.
Here's the working script:
import bpy
bpy.app.handlers.depsgraph_update_post.clear()
previous_objects = set(bpy.data.objects)
def add_triangulate_modifier(obj):
for mod in obj.modifiers:
if mod.type == "TRIANGULATE":
return
mod = obj.modifiers.new(name="Triangulate", type='TRIANGULATE')
def new_object_added(scene):
global previous_objects
current_objects = set(bpy.data.objects)
new_objects = current_objects - previous_objects
previous_objects = current_objects
if not new_objects:
return
for obj in new_objects:
print("New object added: ", obj.name, type(obj))
add_triangulate_modifier(obj)
bpy.app.handlers.depsgraph_update_post.append(new_object_added)
- 10,995
- 8
- 23
- 51
-
This script is working on it's own, however in an addon I am not able to get it to work. I am recieving the error "'AttributeError: '_RestrictData' object has no attribute 'objects'"
I've tried moving all the code in the init file and putting this in the register function: "bpy.app.handlers.depsgraph_update_post.append(new_object_added)"
– Zak Nelson Feb 20 '23 at 22:42 -
@ZakNelson because you are trying to access
bpy.data.objectsbefore the registration has completed wherebpy_datastill is in the state<class 'bpy_restrict_state._RestrictData'>. https://blender.stackexchange.com/a/8732/142292 – Harry McKenzie Mar 24 '24 at 23:49