|
|
|
 |
Reply From: |
uaknight |
I agree that it would be convenient to have static variables. These should be common to the class, not the object, just like constants. But contrary to constants, it should be possible to modify them.
I suggest that a var declaration could be prescribed with the static key word:
const MY_CONST # shared with all objects of this class, non-modifiable (existing)
static var my_static_var # shared with all objects of this class, modifiable (suggested)
However, as a workaround, it’s possible to use the metadata for the gdscript of the class. Metadata is a dictionary which every Object in Godot has. Since a GDScript is a Resource and a Resource inherits from Object, also the gdscript (the class itself) has a metadata dictionary as a member.
Here’s an example from my game. I have a number of factions and each faction should start the game with 2 scout units each. I want the names of the scout units to be like “1st Scout”, “2nd Scout”, “3rd Scout”, “4th Scout”, where 1st and 2nd belongs to the first faction, 3rd and 4th belongs to the second faction, and so on. The order number of the scout unit should reflect the total number of units having been created so far of the scout class.
To achieve this, I put a counter variable in the metadata of the Scout gdscript.
I put the scout generation in the Faction script and it looks like this:
const SCOUT_TEMPLATE = preload("res://squad/Scout.tscn")
func setup(game):
# create scouts
for i in 2:
var scout = SCOUT_TEMPLATE.instance()
var scout_class = scout.get_script()
var counter = scout_class.get_meta("counter")
counter += 1
scout.number = counter
scout.name = scout.get_unit_name("Scout")
scout_class.set_meta("counter", counter)
scout.faction = self
game.squad_node.add_child(scout)
pass
func _ready():
var scout_class = load("res://squad/Scout.gd")
if not scout_class.has_meta("counter"):
scout_class.set_meta("counter", 0)
pass
For each scout unit created, the class counter is fetched from the metadata of the class, it is increased by 1, and then saved back into the metadata.
The get_unit_name(“Scout”) function generates the name, like “1st Scout”.