I'm trying to add a checker in my script
e.g.
SceneManager.gd
# This script manage scenes, need to run as @@ Singleton script @@
func _ready():
if not is_autoloaded():
print("[error] this scripts should run as autoload script !!!")
Is there a function to check if current script is autoloaded ?
Not directly, but this can be accomplished with a script like this (autoloaded as "Autoloaded"):
extends Node
var loaded = false
func _ready():
if Autoloaded.loaded:
printerr("[error] this scripts should run as autoload script !!!")
else:
Autoloaded.loaded = true
This code:
Will fail if the script is not autoloaded (since it accesses its autoloaded instance).
Will print an error if there is more than one instance (allowing only the autoloaded one).
By the way, GitHub isn't a support forum, typically it would be better to ask these questions elsewhere. However, I'll leave this open in case we wanted to add something like is_autoloaded.
That is epically hard to know, it needs to be added to docs and a is_autoloaded function would be VERY welcome (hint hint )
@aaronfranke Thanks
I've been thinking about how one could implement this. The problem is that Singleton Nodes are just normal Nodes at runtime.
One way to do it would be to just add a property is_autoloaded to the Node class that is set to true after an autoloaded Node is instantiated. This, of course, has the downside that it would be easy to manipulate that value from the outside.
SceneTree could also create and hold a list of autoloaded Nodes.
Reading and comparing Autoloads from ProjectSettings at runtime will only work if the name of the autoloaded Nodes is never changed.
One could also try to check ScriptServer for matching globals but then this would only work with Autoloads that have "Singleton" enabled, and depends on the registered script languages. I also couldn't find an easy way of retrieving globals directly from ScriptServer.
Any thoughts on this?
This should work:
func _ready():
# Autoloads are always children of the SceneTree's root node and not the SceneTree's current_scene
if get_parent() == get_tree().root and self != get_tree().current_scene:
print("This is an autoload %s" % name)
else:
print("This is NOT an autoload %s" % name)
@mrcdk Thanks, this helps me out
Most helpful comment
That is epically hard to know, it needs to be added to docs and a is_autoloaded function would be VERY welcome (hint hint )