2
$\begingroup$

I would like to create an object and add a geometry node modifier to it (with an already existing node tree) via script.

$\endgroup$

2 Answers 2

2
$\begingroup$

There are several ways to do this. Here is an example of one approach:

import bpy

# 1) Create the object
# Replace this with code that creates the object you want.
bpy.ops.mesh.primitive_monkey_add()

# The op makes the object the active object. So use it
# If you didn't create the object in a way that does make
# it active, replace this statement with code that selects it.
object = bpy.context.active_object

# 2) Add the GeometryNodes Modifier
modifier = object.modifiers.new("GN Test", "NODES")

# Locate the node tree you want to add to the modifier
# Replace this with code to find the node tree you want to use
replacement = bpy.data.node_groups["replacement"]

# 3) Replace the modifier's node group with the replacement
modifier.node_group = replacement

This code assumes that there is a replacement node tree and that in the example it is called "replacement". Replace that text string with the name you've given the node tree or find the node tree in some other way that is appropriate.

There are many ways you might create the object. Not all of them make the created object the active object. If you use one of the alternatives, you have to identify the object some other way.

Finally, this uses a NodesModifier by calling modifiers.new, a function that takes two arguments. "NODES" is the correct argument for a GeometryNodes modifier.

$\endgroup$
2
$\begingroup$

Create a new Geomod on your object

bpy.data.objects['obj_name'].modifiers.new('mod_name',type='NODES')

Create a pointer to the node tree

tree = bpy.data.node_groups['node_tree']

Set that tree to your modifier

bpy.data.objects['obj_name'].modifiers['mod_name'].node_group = tree
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.