Export node path to a singleton for access by other nodes?

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

Is it possible to esport a node path to a singleton script so that it can be accessed by other nodes even if it changes its position in the tree?
Let’s say I have a node which is is being accessed by other nodes via get_node. In get_node I’m prviding full paths from root. But, if that node needs to move for any reason (eg, I want to reparent it) the path will change and I will have to update the path in all scripts currently accessing the node. I’m looking for a way to make godot find the node wherever it happens to be in the tree. I was thinking, if I could somehow export its path to a global singleton and access it from there?

:bust_in_silhouette: Reply From: Macryc

right, here’s how i got it to work (let me know of there is an easier way):

Singleton script

onready var path_to_node


Sought Node script

func _ready()
Singleton.path_to_node = self.get_path()


Other nodes (which need to access sought node)' script

var sought_node = get_node(Singleton.path_to_node)
:bust_in_silhouette: Reply From: Magso

Storing the path in a singleton will still loose reference once the node is moved unless it is updated. An easier way to do this is to store the node itself in the singleton and use get_path() if necessary. It is also possible to use find_node() like this

get_node("/root/scene node").find_node("name of node")

wow, didnt know you could find nodes that easily in a hierarchy. I need to try this. Thanks!

Macryc | 2020-03-20 10:40