@export & @onready
Two annotations appear in almost every Godot script. @export turns a variable into a property you can edit in the Inspector, so designers tune speed, health and loot without opening code. @onready delays a variable's initialiser until the node enters the tree and its children exist, which is the standard way to grab child nodes.
@export: properties in the Inspector
extends CharacterBody2D
@export var speed := 120.0 # shows as a number field, default 120
@export var max_hp: int = 5Select the node in a scene and both fields appear at the top of the Inspector under the script's name. When you change a value there, the scene file stores the override; the script's value stays the default. That is why two instances of enemy.tscn in one level can have different speeds:
[node name="Slime" parent="." instance=ExtResource("2_slime")]
position = Vector2(240, 96)
speed = 60.0Only the overridden speed is written. If you later change the default in the script to 150.0, every instance that didn't override it picks up the new value.
An exported variable needs a type the Inspector can edit: write it (: int) or give it an initial value Godot can take the type from (:= 120.0). A bare @export var x with neither is a parse error ("Cannot use simple "@export" annotation with variable without type or initializer").
The export family
Plain @export picks an editor from the type. The specialised annotations add a hint: a slider range, a drop-down, a file picker. This script exports one of each and then lists its own properties with the hint the Inspector receives:
extends Node2D
# frames: 0
enum Team { RED, BLUE }
@export var speed := 120.0
@export_range(0, 100, 5) var armor: int = 10
@export_range(0.0, 1.0, 0.01, "or_greater") var crit_chance := 0.05
@export var team: Team = Team.BLUE
@export_enum("Sword", "Bow", "Staff") var weapon: String = "Bow"
@export_group("Audio")
@export_file("*.ogg", "*.wav") var hit_sound: String
@export var volume_db := -6.0
@export_group("")
@export var target: Node2D
@export_node_path("Camera2D") var camera_path: NodePath
@export var loot: Array[String] = ["coin"]
@export_multiline var bio := ""
@export_flags("Fire", "Water", "Earth") var resist := 0
func _ready():
for p in get_property_list():
if p.usage & PROPERTY_USAGE_SCRIPT_VARIABLE:
print("%-12s %-9s %s" % [p.name, type_string(p.type), p.hint_string])speed float
armor int 0.0,100.0,5.0
crit_chance float 0.0,1.0,0.01,or_greater
team int Red:0,Blue:1
weapon String Sword,Bow,Staff
hit_sound String *.ogg,*.wav
volume_db float
target Object Node2D
camera_path NodePath Camera2D
loot Array 4:
bio String
resist int Fire,Water,Earth
| Annotation | Inspector shows |
|---|---|
@export_range(min, max, step) |
a slider; extra hints "or_greater", "or_less", "suffix:px", "exp" |
@export var e: MyEnum |
a drop-down with the enum names (stored as an int) |
@export_enum("A", "B") |
a drop-down for an int or String without declaring an enum |
@export_file("*.json"), @export_dir, @export_global_file |
a file or folder picker (path as a String) |
@export_multiline |
a multi-line text box |
@export_color_no_alpha |
a colour picker without alpha |
@export_flags("A", "B", "C") |
check boxes stored as bit flags (1, 2, 4) |
@export_flags_2d_physics |
the named 2D physics layers, for collision masks |
@export_group("Name"), @export_subgroup, @export_category |
foldable sections; @export_group("") ends a group |
@export var node: Node2D |
a node picker restricted to that type (a direct node reference) |
@export_node_path("Camera2D") |
a node picker that stores a NodePath |
@export var stats: EnemyStats |
a resource slot (see Resources & .tres Files) |
@export_tool_button("Bake") (4.4+) |
a button that calls a Callable in the editor; needs a @tool script |
Export node references directly. Since Godot 4.0, @export var target: Node2D stores a reference to another node in the same scene, fixed up automatically when you move or rename it. That beats hard-coded get_node("../../Player") paths, which break silently when the tree changes.
Note: An exported property is set after
_init()runs and before_ready(). If a setter on an exported variable touches child nodes, checkis_node_ready()first, because the setter also runs while the scene is loading.
@onready: wait for the tree
When a node's _init() runs, it is not yet in the tree and, for nodes loaded from a scene, its children don't exist yet. So var sprite = $Sprite at class level would fail. @onready runs the initialiser just before _ready(), when children are there:
extends Node2D
# frames: 0
@onready var sprite: Sprite2D = $Body/Sprite
@onready var health_bar := %HealthBar as ProgressBar
@onready var start_x := position.x
func _init():
# In a real project these children come from the .tscn file.
var body := Node2D.new()
body.name = "Body"
add_child(body)
var s := Sprite2D.new()
s.name = "Sprite"
body.add_child(s)
var ui := CanvasLayer.new()
ui.name = "UI"
add_child(ui)
var bar := ProgressBar.new()
bar.name = "HealthBar"
ui.add_child(bar)
bar.owner = self
bar.unique_name_in_owner = true
position = Vector2(32, 0)
print("_init: sprite = ", sprite)
func _ready():
print("_ready: sprite path = ", get_path_to(sprite))
print("_ready: health bar = ", health_bar.name, " max ", health_bar.max_value)
print("start_x = ", start_x)_init: sprite = <null>
_ready: sprite path = Body/Sprite
_ready: health bar = HealthBar max 100.0
start_x = 32.0
$Body/Spriteis shorthand forget_node("Body/Sprite"), a path relative to this node.%HealthBarfinds a scene-unique node: in the Scene dock, right-click a node and choose Access as Unique Name. The%lookup keeps working when you move the bar to another parent, which$UI/HealthBarwould not. (The example setsownerandunique_name_in_ownerin code, which is what the editor saves for you.)@onreadyvalues are computed in order, top to bottom, so later ones can use earlier ones.
Don't combine @export and @onready on one variable: the @onready value would overwrite whatever the Inspector set, and Godot reports it (the ONREADY_WITH_EXPORT warning, an error by default).
Typical script header
Most node scripts start with the same layout, in this order: class_name/extends, signals, enums and constants, exports, regular variables, @onready variables, then the built-in callbacks:
class_name Player
extends CharacterBody2D
signal died
const JUMP_VELOCITY := -320.0
@export var speed := 140.0
@export_range(1, 10) var max_hp := 3
var hp := max_hp
@onready var sprite: AnimatedSprite2D = $AnimatedSprite2D
@onready var hurt_sound: AudioStreamPlayer2D = %HurtSound
func _ready() -> void:
sprite.play("idle")This matches the official GDScript style guide, and it means anyone opening the file sees the "knobs" (exports) first.
Test yourself
You change @export var speed := 120.0 to 150.0 in the script. Which instances change speed?
- All instances
- Only instances whose speed was not overridden in the Inspector
- None until you re-add them to the scene
- Only the first instance
Why does var sprite = $Sprite (without @onready) usually fail?
$only works in_process- The initialiser runs when the object is created, before the node's children exist and before it is in the tree
- Sprites can't be stored in variables
- It needs a type hint
What does %HealthBar look up?
- A node named HealthBar anywhere in the whole game
- A node marked 'Access as Unique Name' in the same scene, wherever it sits in that scene's tree
- A percentage property
- An autoload