A static variable is a variable that belongs to a class itself, not to instance 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:
class_name Mob
static var mob_count := 0
var my_index := 0
func _init():
mob_count += 1
my_index = mob_count
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:
func _ready() -> void:
var mob_instance = Mob.new()
print(mob_instance.my_index)
Or get a reference to one of the existing mobs:
@onready var mob_instance = $Mob
func _ready() -> void:
print(mob_instance.my_index)
Another slightly more advanced use is when applying the Blackboard Pattern (Game AI) pattern for game AI. You can use static variables to store the data shared between all the AI agents in the game.
class Blackboard extends RefCounted:
static var player_died: Signal
static var player_global_position := Vector3.ZERO
static var is_player_dead := false:
set = set_is_player_dead
static func set_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 Setters and Getters 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 GDScriptStatic 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 extends RefCounted:
static var player_died: Signal = (func ():
(Blackboard as RefCounted).add_user_signal("player_died")
return Signal(Blackboard, "player_died")
).call()
See Also
Related terms in the Glossary