A static variable is a variable that belongs to a class itself, not to instances of the class. This means that all class instances share the same value for the variable. You can think of a static variable as a global variable accessible through the class in which it's defined.
You use static variables to store data that you need to share between all instances of a class. For example, you could use one to keep track of the number of mobs that have spawned on the field and limit the number of mobs that can be spawned at once.
To define a static variable in GDScript, you use the static keyword before the variable definition. Here's an example of a static variable that keeps track of the number of mobs spawned in a game:
In this example, mob_count is shared by all mobs, whereas my_index is unique to each mob instance. You can access the static variable from outside the class by using the class name followed by the . operator and the variable name. Here's an example of the player accessing the mob_count variable:
func_ready():print(Mob.mob_count)
However, my_index is only available to instances of the Mob class. To access them, you would need to create a new mob:
Another slightly more advanced use is when applying the pattern for game AI. You can use static variables to store the data shared between all the AI agents in the game.
class Blackboard extendsRefCounted:staticvar player_died: Signal
staticvar player_global_position :=Vector3.ZEROstaticvar is_player_dead := false:
set = set_is_player_dead
staticfuncset_is_player_dead(new_value:bool)->void:
is_player_dead = new_value
if is_player_dead:
player_died.emit()
In this example, we have a class that stores the player's position and whether the player died and makes that data accessible to all the AIs or mobs in the game.
As you can see, you can associate a with a static variable to run additional code when setting the variable, just like you would with a regular variable. Here, the setter emits a signal when the player dies.
Caution, there are no static signals in GDScript
Static signals do not exist (at the time of writing this text, Godot 4.4), so the code above requires some massaging to create a static signal. You can use an Immediately Invoked Function Expression (IIFE), a lambda function that creates a custom signal and assigns it to the class, like so:
class Blackboard extendsRefCounted:# ...staticvar player_died: Signal =(func():(Blackboard as RefCounted).add_user_signal("player_died")returnSignal(Blackboard,"player_died")).call()