Is there a way in GDScript to detect if another script is loaded or not?

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

For example, I have a script A that implemented stuffs and add it to AutoLoad.
In another script B, I call A.func().
But script B can also be used without script A.
I know AutoLoad will make script A always be there. But I also want script B to be more like a flexible module. And it can still run if I remove script A from AutoLoad.

I found there is type_exists to check if a class is in ClassDB or not. But it doesn’t solve the script checking part. Or checking if any var exists or not.

finding something like:

# in a script
var other_script = get_script_from_current_scope("OtherScriptName")
var data = null
if other_script == null:
    print("OtherScriptName not exists, feature X is disabled")
    data = other_script.get_data()
:bust_in_silhouette: Reply From: Lopy

To know if a Script, or any other Resource, is currently loaded, you can use ResourceLoader.has_cached().

However, I believe this isn’t what you are trying to check.

Setting a Script as an Autoload tells Godot to create an instance of it when the game starts, that should persist through scene changes, and is a direct child of the “root” node in the SceneTree. Your tree looks like that:


To better see what is happening, start your game, then focus the Editor without closing the game, and just above the tree view on your left, select “Remote”. This will show you the tree of your game as it is running. You can also call $"/root".print_tree_pretty() (inside some Node’s _ready()) for a textual representation.

This means that writing A.func() is the same* as get_node("/root/A").func(). Your code would then look like this:

var a = get_node_or_null("/root/A")
if is_instance_valid(a):
    print("No script instanced through the Autoload mechanism under the name A, feature X is disabled")

*neglecting access speed