2
$\begingroup$

I wanted to create a geometry node tree using my script and modify this tree. As I understand, you need the name of the tree to edit it.

I tried assigning bpy.ops.node.new_geometry_nodes_modifier() to a variable, but this function just returns {'FINISHED'}. Moreover, I cannot supply a name to the geometry node tree using bpy.ops.node.new_geometry_nodes_modifier() because it does not have a name argument. Is there a way to get the name of this newly created tree?

Kind regards, Rohit

$\endgroup$
1
  • 3
    $\begingroup$ You can create a modifier without an op: ob.modifiers.new("My Modifier Name", 'NODES'). This returns the new modifier. $\endgroup$
    – scurest
    Commented Jan 12, 2022 at 20:47

2 Answers 2

3
$\begingroup$

Use the low-level function to add modifiers: https://docs.blender.org/api/current/bpy.types.ObjectModifiers.html#bpy.types.ObjectModifiers.new

import bpy

obj = bpy.context.scene.objects['Cube']
geo_mod = obj.modifiers.new(name="GeometryNodes", type='NODES')

print(geo_mod.name, geo_mod)
# GeometryNodes <bpy_struct, NodesModifier("GeometryNodes") at 0x600000518a58>

NodesModifier.node_group returns the node tree: https://docs.blender.org/api/current/bpy.types.NodesModifier.html#bpy.types.NodesModifier.node_group

tree = geo_mod.node_group
nodes = tree.nodes

for n in nodes:
    print(n.name, n)

# Group Output <bpy_struct, NodeGroupOutput("Group Output") at 0x7fcf5090aeb8>
# Group Input <bpy_struct, NodeGroupInput("Group Input") at 0x7fcf5090c008>
$\endgroup$
2
$\begingroup$

Bpy ops seem to never return the thing they've created. The modifier is created attached to the active object, so to find it quickly use

bpy.context.active_object.modifiers[-1].node_group

-1 works because you've just created the modifier so it's the last one in the group. Replace -1 with 'GeometryNodes' at other times.

If you use 'GeometryNodes' be aware that it is possible for a give object ot have multiple geometry node modifiers, so you have to figure out if you have the right one.

If you don't know whether the active object has a Geometry Nodes modifier, than the name lookup will fail if it doesn't. It will also fail if the user had changed the name of the modifier.

You can use

next(m for m in C.active_object.modifiers if m.type=='NODES')

to get the first (the highest on the stack) geometry nodes modifier, or an error if there's no geonodes mods on the stack. You can also use

next(m for m in C.active_object.modifiers if m.type=='NODES', None)

to get None instead of an error. Or you can use

[m for m in C.active_object.modifiers if m.type=='NODES']

to get a list of all geonodes modifiers.

$\endgroup$
1
  • $\begingroup$ Thanks for the update Markus von Broady. $\endgroup$ Commented Jan 12, 2022 at 22:08

You must log in to answer this question.

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