How to access other nodes in a scene

Godot Version

4.7

Question

I’m fairly new to Godot, and I want to set up an NPC scene that can access nodes from its parent scene. Basically, I have an NPC that uses an array of marker 2D nodes to determine locations it can travel to. Currently, I have to set up that array manually and have to load in the markers by hand in order for it to be added to the array. I want to make it so that the NPC can automatically read the location of these nodes when it loads into any scene.

What I’m not sure how to accomplish is the best way to access those nodes through code. My scene is structured like this:

and I want the script of the NPC character to access each of the destinations and add them as an array.

Any help is appreciated!

Put destination nodes in a group and call get_tree().get_nodes_in_group(...) from the npc script. It will return node references in an array.

Thank you. I added a group to the markers, and created the var with:

@export var destinations: Array[Marker2D]

and then assigned the value with:

destinations = get_tree().get_nodes_in_group(“npc_locations”)

This results in an error that the group is not declared within the current scope. If the group exists within the level scene, and get_tree() is accessing that level, then wouldn’t the group be within the accessible scope? Not sure what piece I’m missing here.

How did you put the nodes into the group?
What’s the exact error message?
How does your remote scene tree look at runtime?

It’s strange, I reopened the project and I’m no longer getting the error about the node being out of scope, but the line

destinations = get_tree().get_nodes_in_group("npc_destinations")

results in the error:

Error at (27, 20): Value of type “Array[Node]” cannot be assigned to a variable of type “Array[Marker2D]”.

However, if I run

print(get_tree().get_nodes_in_group("npc_destinations"))

it prints out an array of the Marker2Ds in my group like I want. Is this array actually returning nodes that only appear like Marker2Ds when printed?

That’s a type mismatch. get_nodes_in_group() returns an array of Node but you’re trying to assign it to an array of Marker2D. Either assign to Array[Node] (or an untyped array) or cast to Array[Marker2D]