A function that add a GN modifier to a mesh object and assign a specific node from a blend file.
import bpy
from os.path import join as os_path_join
def add_gn_modifier_with(obj, file_path, node_name, method="LINK"):
if hasattr(obj, "type"):
if obj.type != "MESH":
print("MESH object only")
return
else:
print("Invalid object")
return
if file_path == bpy.data.filepath:
print("Not allow load library from current file")
# Don't append current file, It will crash blender even the code inside the try:
return
inner_path = "NodeTree"
node_groups = bpy.data.node_groups
def wm_append(link=True):
try:
bpy.ops.wm.append(
filepath=os_path_join(file_path, inner_path, node_name),
directory=os_path_join(file_path, inner_path),
filename=node_name,
link=link)
except Exception as ex:
# file_path or node_name may wrong
print(str(ex))
return False
return True
if method == "LINK":
name_tuple = node_name, file_path
if name_tuple in node_groups:
pass
# Already Linked
else:
if not wm_append(link=True):
return
if name_tuple in node_groups:
node = node_groups[name_tuple]
else:
print("node group not found in the file_path")
return
elif method == "APPEND":
if node_name in node_groups:
old_node_groups = set(node_groups)
if not wm_append(link=False):
return
try:
node = next(ob for ob in node_groups if ob not in old_node_groups)
except:
print("node group not found in the file_path")
return
else:
if not wm_append(link=False):
return
if node_name in node_groups:
node = node_groups[node_name]
else:
print("node group not found in the file_path")
return
elif method == "REUSE":
print("Unsupport method")
return
else:
print("Unsupport method")
return
if node.type != "GEOMETRY":
node_groups.remove(node)
print("Wrong Node Type")
# you may want to check if the node marked as asset
return
md = obj.modifiers.new(node_name, "NODES")
md.node_group = node