Can you save a node path to a variable?

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

Is it possible to save a node path to a variable? Like if you need to frequently to the grandparent of a node and to don’t want to use get_parent().get_parent.get_node() every tiime

:bust_in_silhouette: Reply From: gmaps

Yes, it’s possible. You can do it in multiple ways

var grandparent_child = get_parent().get_parent().get_node("nodename")
var grandparent_child = $"../../nodename"

or if it’s something you use across different nodes, you could save it’s reference to a global singleton: in the wanted node you can set: Globals.set("nodename", self). And then use Globals.get("nodename") in any node you want.

You can also export node path and assign it from editor:

export(NodePath) var player_node_path
var player_node

func _ready() -> void:
    player_node = get_node(player_node_path)

Vrzasq | 2019-09-12 11:42

Awesome, thanks it worked. Also thanks to Vrzasq, that looks useful as well.

DJ_Fail87 | 2019-09-13 02:01