Use get_node in a singleton

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By PerduGames
:warning: Old Version Published before Godot 3 was released.

How do I use the code below in a singleton because the singleton is where in the tree? Like that access to the other nodes of it, I’m trying like this and it does not work:

onready var controlSample = get_node("../SamplePlayer2D")
:bust_in_silhouette: Reply From: YeOldeDM

Your singleton(s) are siblings of your main_scene.

If the top node of your main_scene is called Game you access it with an absolute path get_node("/root/Game").

if you have a singleton named Global you access it with an absolute path get_node("/root/Global").

But know that singletons call _ready() before the main_scene, so you wont be able to access the main_scene within a singleton’s _ready().

You can, however, define a var controlSample in your singleton script. In the main_scene’s script which handles this object, you can have it define itself to the singleton in its _ready():

func _ready():
  Global.controlSample = get_node( "SamplePlayer2D" )

I have recently needed to access the Main node from an autoload singleton file. When I try what is suggested above, I get an error saying I cant use Absolute Paths outside of the SceneTree.
What can I do?

ondesic | 2020-08-07 15:20

I have the same problem

Kushal | 2022-01-15 16:53