I have a script in Godot that I am turning into a singleton. I have trouble when I try to run the project from its base, as the singleton cannot find the nodes needed.
Is there a way I can call these get_node functions from root or something similar, instead of what I am currently doing below?
onready var NameVar = get_node('Panel/HBoxContainer/RootVboxPlayerPreferences/Label/VBoxPlayerPreferances/DisplayNameLineEdit')
By singleton you mean autoload, correct?
Here is the thing: autoloads are siblings of the current scene. The current scene can change and autoloads remain in the scene tree. So the scene you might be trying to reach from the autoload might not be there (in fact, on ready, it won't, since autoloads are loaded before the current scene). Furthermore, the name of the current scene is the name of the current scene, and by that I mean it has no special name.
By the way, the parent of the current scene and also of the autoloads is a Viewport
called root
(when you use get_viewport
, by default, you are getting that one). So if you want to use an absolute path (instead fo a relative path), it would be something like "/root/name_of_current_scene/path/to/node"
. Similarly the autoloads will be at "/root/name_of_autoload"
.
Now, what I would suggest you to do is not use an script as autoload, but use an scene as autoload. In project setting, on the AutoLoad tab, when you are going to add an autoload, you can pick an scene (e.g. a .tscn file) instead of a script. The root of the scene can, of course, have the script you want, and it can also have whatever other nodes it needs to work.