Setting variables equal to export variables

Godot Version

4.2

Question

I’ve noticed that whenever I build a component with an export variable and then set another variable equal to the export variable, the normal variable is always the export variable’s default value, even if I change it in the editor. For example, if I have a health component with these two lines:

@export var max_health = 5
var health = max_health

then even if I set max_health to something different in the editor, health is always set equal to five. I’ve come up with workarounds for this issue where it’s necessary, but is there a way to resolve it completely?

This is over simplification of how resources are initialized:

  1. Load the data. var data = load('path/to/resource')
  2. Initialize associated scripts. TheScript.new()
  3. Assign script values from the scene: the_script.max_health = data.max_health

max_health and health is initialized in the TheScript.new() stage. This sets max_health = 5 and then health = 5.

The following step then sets max_health = data.max_health which does not update health.

Suggestion

You should set health at a later stage. One option is the _ready function or stage:

@onready var health = max_health
# or
func _ready():
  health = max_health
2 Likes