GDScript Fundamentals

Lesson 6 of 7

Classes and Inheritance

Beyond scripts attached directly to nodes, GDScript supports full custom classes, letting you define reusable data types and share behavior through inheritance.

# item.gd
class_name Item
extends Resource

@export var name: String
@export var value: int

func describe() -> String:
    return "%s (%d gold)" % [name, value]

class_name Item registers this script as a globally-available type named Item, usable anywhere in the project without an explicit preload. Extending Resource (rather than a scene node type) makes it a reusable data asset, perfect for things like item definitions that don't need a position in the game world.

Inheriting your own classes

# weapon.gd
class_name Weapon
extends Item

@export var damage: int

func describe() -> String:
    return super.describe() + " - %d damage" % damage

Weapon extends Item inherits name, value, and the base describe(), then overrides describe() with its own version. super.describe() calls the parent class's original implementation first, then extends its result, rather than throwing it away entirely, a common pattern when a subclass wants to add to behavior instead of fully replacing it.

var sword = Weapon.new()
sword.name = "Iron Sword"
sword.value = 50
sword.damage = 12
print(sword.describe())   # "Iron Sword (50 gold) - 12 damage"

📝 Classes and Inheritance Quiz

Passing score: 70%
  1. 1.What does class_name Item do?

  2. 2.super.describe() calls the parent class's original method instead of the overriding one.

  3. 3.A custom GDScript class inherits from another with the keyword: ____ Item