Topic was automatically imported from the old Question2Answer platform.
Asked By
VictorSeven
Old Version
Published before Godot 3 was released.
I have a singleton, correctly added to Autoload in Project Settings. Moreover, I have used it in several scenes and it is working fine.
Now, I want to instance a node that has to load this singleton. I provide you a minimal working example for my problem.
This the script that I have. It is not a singleton. From here, I will instance scene_with_singleton.tscn:
var packed = preload("res://scene_with_singleton.tscn")
var scene = packed.instance()
var a = 5
scene.init_stuff(a) #Error comes from here
add_child(scene)
Then, in the scene_with_singleton.tscn I have:
var singleton
func _ready():
pass
func init_stuff(a):
#my_singleton.gd was added to Autoload
singleton = get_node("/root/my_singleton")
singleton.call_stuff(a)
When I do this a get a Attempt to call function 'call_stuff' in base 'null instance' on a null instance.. I suspect that the problem lies in the order Godot is loading the stuff, but I don’t know how to overcome it.
I have read this, which is exactly the same problem I am having, but I don’t understand which is the solution.
You are adding the scene_with_singleton as a child of that script (which I guess is an autoloaded node).
So the path to the node you want may be another (take a look at the remote inspector).
Why don’t you just load the scene in autoload?, if need some extra processing, keep a script checking if all your autoloaded scenes are ready and process them after that.
And when initializing things (in particular when not dealing with children), always check has_node before trying to use it, keep checking until is in there.
No, the script from which I call scene_with_singleton is not the singleton itself, and it is not autoloaded. I have edited the question to make it clearer.
The autoloaded script manages shared classes between the code and it doesn’t have any scene associated. So I am simply interested to know where the error comes from and what I have to do to solve it.
I was able to solve the problem. The problem was pretty basic: when I instance() the packed scene, it has not yet entered the SceneTree, so I cannot get nodes. So I have to do the add_child() first.
Complete solution:
#In my script, which is not a singleton:
var packed = preload("res://scene_with_singleton.tscn")
var scene = packed.instance()
add_child(scene)
var a = 5
scene.init_stuff(a)
In the script I instance,
var singleton
func _ready():
#It is more natural to load the singleton here, but it does not matter...
singleton = get_node("/root/my_singleton")
func init_stuff(a):
singleton.call_stuff(a)