Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท GDScript

GDScript Classes, Inheritance and @export Variables

Learn how GDScript classes work in Godot 4: extends, class_name, inner classes, inheritance, super, @export, @onready, setters and getters, static typing and the is operator.

In GDScript, every script file is a class. When you attach player.gd to a node, you are extending that node's class with your own properties and methods. This is the main way you add behavior to Godot. This lesson covers extends, class_name, inheritance, the special @export and @onready annotations, and properties with setters and getters.

GDScript only runs in Godot, so the code is read-only. The Python stand-in at the end models inheritance, super() and "exported" defaults so you can try the ideas.

A script is a class

GDSCRIPT
# player.gd
class_name Player
extends CharacterBody2D

var speed := 220.0

func take_damage(amount: int) -> void:
    print("Ouch: ", amount)
  • extends CharacterBody2D makes Player a kind of CharacterBody2D, so it inherits all its properties (velocity, position) and methods (move_and_slide()).
  • class_name Player registers a global name. Now any script can write var p: Player, p is Player or Player.new(), and the editor lists it in the "Create Node" dialog. Without class_name, other scripts refer to it with preload("res://player.gd").
  • Order matters: class_name first (optional), then extends, then members. Put annotations such as @tool above them.

You can also extends another script: extends "res://base_enemy.gd" or, with a class name, extends BaseEnemy.

Inheritance and super

GDSCRIPT
# base_enemy.gd
class_name BaseEnemy
extends CharacterBody2D

@export var health := 30

func take_damage(amount: int) -> void:
    health -= amount
    if health <= 0:
        die()

func die() -> void:
    queue_free()
GDSCRIPT
# boss.gd
class_name Boss
extends BaseEnemy

func take_damage(amount: int) -> void:
    super(amount / 2)        # bosses take half damage, then use the parent's logic

func die() -> void:
    print("Boss defeated!")
    super()
  • A child class overrides a method by defining it again with the same name and parameters.
  • super() or super(args) calls the parent version. Use it in lifecycle overrides too: func _ready() -> void: super().
  • Godot's built-in functions such as _ready and _process are virtual methods; overriding them hooks into the engine. Because each script's _ready runs separately for base and child, a derived class that defines _ready normally calls super() if the parent also needs setup.

Check types with is and cast with as:

GDSCRIPT
func hit(body: Node) -> void:
    if body is BaseEnemy:
        (body as BaseEnemy).take_damage(10)

Prefer composition (small nodes with their own scripts) over deep inheritance trees. Two or three levels is plenty.

@export: variables in the Inspector

@export shows a variable in the Inspector, where designers can change it per instance without touching code. The value is saved in the scene.

GDSCRIPT
@export var speed := 220.0
@export var max_health: int = 100
@export var title := "Hero"
@export var color := Color.WHITE
@export var enemy_scene: PackedScene
@export var target: Node2D                    # drag a node here (node reference)
@export var weapon_icon: Texture2D
@export_range(0.0, 1.0, 0.05) var volume := 0.8
@export_range(1, 10) var lives := 3
@export_enum("Easy", "Normal", "Hard") var difficulty := 1
@export_file("*.tscn") var next_level := ""
@export_multiline var notes := ""
@export_flags_2d_physics var mask := 1
@export var drops: Array[ItemData] = []
@export_group("Combat")
@export var damage := 5
@export_subgroup("Resist")
@export var armor := 2

Useful details:

  • A typed default (:= 220.0 or : int = 100) is required for the Inspector to pick the right editor.
  • Changing the default in the script does not change instances that already stored a value in the scene. Reset it with the revert arrow in the Inspector.
  • @export_range creates a slider; @export_enum a drop-down; @export_group organizes long lists.
  • @export of a node (@export var target: Node2D) is more robust than a hard-coded path: you can rearrange the tree without breaking it.

@onready: wait for the tree

GDSCRIPT
@onready var sprite: Sprite2D = $Sprite2D
@onready var health_bar: ProgressBar = %HealthBar     # unique name

An @onready variable's initializer runs just before _ready. Use it for child nodes, as children do not exist when member variables are first created.

Properties: setters and getters

GDSCRIPT
var health := 100:
    set(value):
        health = clampi(value, 0, max_health)
        health_changed.emit(health)
    get:
        return health

var is_alive: bool:
    get:
        return health > 0

signal health_changed(new_value: int)
@export var max_health := 100

Inside the setter, assigning health = ... sets the backing variable directly (it does not call the setter again). The advantage is encapsulation: every part of the game that writes player.health = 500 gets clamping and the signal for free. A getter-only property such as is_alive is computed on demand.

Inner classes and static members

GDSCRIPT
class Stats:
    var hp := 10
    var mp := 5

var stats := Stats.new()

const DEFAULT_NAME := "Hero"
static var instances_created := 0
static func make_default() -> Player:
    return Player.new()

Inner classes group data inside a file. For anything reused, a separate script with class_name is cleaner. static var (Godot 4.1+) is shared by all instances.

Constructors

Give a class an _init method for construction; the engine calls it when you use .new():

GDSCRIPT
class_name Weapon
extends RefCounted

var damage: int

func _init(d: int = 1) -> void:
    damage = d

Weapon.new(5) makes a weapon with damage 5. RefCounted is the base for lightweight objects that are freed automatically; use Node only for things that belong in the scene tree.

Stand-in: inheritance and exports in Python

This is not GDScript, but super(), overriding and per-instance configuration behave the same way.

Python Stand-in (Python): override, super and 'exported' values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Typing class_name twice for different files (names must be unique across the project).
  • Using @export without a default or a type, so the Inspector cannot decide the editor.
  • Reading $Sprite2D in a member initializer without @onready.
  • Forgetting super() and silently skipping parent logic.
  • Deep inheritance trees. Prefer small scenes and signals.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does class_name Player do?

    class_name registers a global type, so other scripts can use Player as a type and create instances.
  2. 2. Why use @onready var sprite = $Sprite2D?

    @onready delays the initializer until the node is ready, when its children exist.
  3. 3. How do you call the parent class's version of an overridden function?

    super() (or super(args)) calls the parent implementation.
  4. 4. What does @export var speed := 220.0 do?

    Exported variables appear in the Inspector, can differ per instance and are saved with the scene.

Summary

  • A GDScript file is a class that extends a built-in or custom class; class_name makes it a global type.
  • Override methods and call super() for parent behavior; use is and as for type checks.
  • @export (and @export_range, _enum, _group...) exposes variables to the Inspector; @onready waits for children.
  • Setters and getters keep rules (clamping, signals) in one place; _init is the constructor.
  • Prefer composition to deep inheritance.

Next: Collections and Lambdas