+1 vote

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 getparent().getparent.get_node() every tiime

in Engine by (28 points)

1 Answer

+4 votes
Best answer

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.


by (709 points)
selected by

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)

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.