Topic was automatically imported from the old Question2Answer platform.
Published before Godot 3 was released.
So lets say I have this script
#name of the script is example.gd
var x = 0
var y = 0
static func test1(x_val):
x = x_val
static func test2(y_val):
y = y_val
and lets say I have another script here
extend <insert node type here>
var z = preload("example.gd")
I would get an error that originates in example.gd test and test2 function because x and y are both not defined (even though they are). How can I use variables I initialized earlier in inside the script in static functions?
Update: When I try to preload one script into another, and call a function from the script I preloaded, I get an error saying I can’t call non-static functions. That is why even though static functions aren’t suitable in this case, I tried to use them. If there is a way to use one script from another script, that is more what I am looking for.
Then you have to use Singeltons. Here you can call a Static Class and work with it.
Write a Script “myClass.gd” and then go to your Project Settings and to the Autoload Tab.
Here you add your Script with a Class name for example “Myclass”.
A static function is a global function that is not related to any object. This mechanism is established in other languages, so that’s why GDscript reused it, but I think it would have been a better solution to simply make it possible to declare global functions in a similar way Autoloads are declared, because it would avoid this kind of confusion.
Your test1 and test2 functions could be declared anywhere, the only thing that would change is how to call them. They aren’t related to any object, so the properties of the surrounding class are invisible to them.
People were of course quick to point you in the direction of Autoloads and Singletons, but I would recommend that you think about why you need static variables in the first place. There are cases where it makes sense to use them, but most of the time when beginners are asking about them it’s because they didn’t see how they can make it work without them and why a solution without Singletons might be better.