Setters and Getters in an autoloaded scene

Godot Version



So I was curious, is it worth while to put set and get functions within an autoloaded scene? I’m using an autoloaded scene to store player data (such as stamina and max stamina) and I’m debating on whether or not having a set and get function for certain variables is better than just referencing it directly.

I want to get the players current stamina value in an autoloaded scene called PlayerData. Should I just reference it directly with PlayerData.stamina or use a get function like PlayerData.get_stamina().


Good day.
setters and getters simply allow you to more flexibly control the sending and receiving of a variable’s value.

For example: if you need to know what value was in a variable before they started changing it, or immediately execute some function after assigning a new value, or simply emit (in the case of set). And get allows, for example, to also track when a value was given, or return it by transforming it.
Whether to create separate functions or not depends on the logic: if you just need to give it or accept a value, and additional logic, then of course create it. And if not, then “under the hood” it does the same thing. And when explicitly specified, the logic simply expands.

ps. getter can also be handy to know for sure that you are getting a value and not accidentally overwrite it.

1 Like

If you want, you can automatically call a getter/setter when calling property.

Here is an example of how to add getters and setters to a property:

signal death
signal health_changed
@export var max_health: float = 100.0
@onready var health: float = max_health:
		return health
		health = clampf(value, 0, max_health)
		if value < 0:

get will be called when getting properties value (example: print(health)), set(value) when setting a value (health = max_health), and both when doing it at the same time (health -= 10.0 ← gets first, sets after calculation)

1 Like