GDScript 2.0: how to export nodes

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By toxicvgl

Edit: I figured out that we can export a node in GDScript 2 simply by:

@export @onready var foo: TheClassYourNodeHas

Amazing! The reason we need a roundabout way in GDScript 1 is just because export(Class) doesn’t work in general.

I leave the original question below:

GDScript 2.0: what is the point of @export_node_path?

I think, in most cases, what we want to get is not a NodePath, but the node at the NodePath.

A sentence:

export(NodePath) onready var foo = get_node(foo) as SomeClass

in GDScript 1 is really useful to “export” a node. But in GDScript 2, we may need to write:

@export_node_path(SomeClass) var foo_node_path
@onready var foo = get_node(foo_node_path) as SomeClass

for the same result; one redundant variable and one more line is needed. Isn’t there more beautiful way to do this?

Edit: One more thing is that we have @export var foo: NodePath already. Is @export_node_path just another way to code it? I am expecting more because it has a class-restricting feature.

I would also like to know this

From what I understand, while it was convenient to write export(NodePath) onready var foo = get_node(foo) as SomeClass, it was not always safe. Like, that code only works if the node path is to a node below the current node, otherwise even onready, it isn’t guaranteed that that node exists yet. But maybe I misunderstood

rossunger | 2022-12-18 22:24

I agree this is not safe. In such case, I write this code in the root node and pass the information to the child who needs it. At least this should not be wrong in terms of OOP.

toxicvgl | 2022-12-18 22:53

:bust_in_silhouette: Reply From: idbrii

what is the point of @export_node_path?

Isn’t the difference between this:

export(NodePath) var foo_path
export(NodePath) onready var foo = get_node(foo_path) as SomeClass

And this:

@export_node_path(SomeClass) var foo_node_path
@onready var foo = get_node(foo_node_path) as SomeClass

That only SomeClass can be picked as values for foo_node_path with export_node_path, whereas the old export version allowed any Node type.

Agreed that it would be more convenient to have @export_node that stores a path, but automatically converts to a Node in ready. But I assume it’s a lot more complex to add hidden variables (since it would essentially generate a hidden foo_node_path), but maybe with the switch to this new annotation syntax that’s still a future possibility.