Reputation: 11
I get the gist of how autoloaded nodes work. They each get plopped into the tree as a singleton first thing, and they're accessible from basically anywhere at runtime using their class names.
Suppose it's not runtime and I'm using a tool script, and I want to use a static function that's part of an autoload which is obviously not in the tree yet - which I can theoretically do because the function is, you know, static. Except I can't, because when I've typed the autoload's class name I'm referring to the singleton instance and not the class. Is there a way to specify the class and not the instance? I don't love scattering functions all over when they could be neatly boxed into one place. I literally just want to print some enums.
I tried changing the class_name so it's different from how the class is referred to in Autoload settings. Let's say the class name is Global
and the autoload is just G
.
I can use G
to get the singleton as usual. Trying to use Global
results in non-existent function in base GDScript
... So that doesn't work, if you were wondering.
Upvotes: 1
Views: 157
Reputation: 48
You can use a class with static functions/variables. The disadvantage is that you can't access the scene tree.
Example static class:
@tool # Neccesary to init variables in editor
class_name StaticClass
## Static class, can be accessed from anywhere (even without autoload).
static var test_var = "blabla"
static func test_func():
print("Static Class! ", test_var)
Example access script:
@tool
extends EditorScript # Used EditorScript for easy execution.
func _run() -> void:
# This code can run from anywhere!
StaticClass.test_func()
StaticClass.test_var = "123"
StaticClass.test_func()
Upvotes: 1