TExcelTAD
Home › Godot 4 with GDScript › Classes, class_name & Enums

Classes, class_name & Enums

Every .gd file is a class. Its first line, extends Something, names the base class, and its variables and functions are the members. Attaching player.gd to a CharacterBody2D node creates one object of that class. You rarely write the word class for these; the file is the class.

This lesson covers naming a script class with class_name, inner classes, inheritance and super, properties with setters and getters, static members, enums, and abstract classes.

class_name: give a script a global name

Without class_name, other scripts must load your script by path (preload("res://enemies/slime.gd")). With it, the class becomes a global type that can be used anywhere, shows up in the Create New Node dialog, and can be used in type hints and is checks:

gdscript
# res://units/unit.gd
class_name Unit
extends Node2D

@export var max_hp := 20
var hp := max_hp

func take_hit(amount: int) -> void:
	hp = maxi(hp - amount, 0)
gdscript
# res://units/knight.gd
class_name Knight
extends Unit            # inherit from your own class by its name

func take_hit(amount: int) -> void:
	super.take_hit(amount - 2)      # armour absorbs 2
gdscript
# anywhere else
func _on_hitbox_body_entered(body: Node2D) -> void:
	if body is Unit:
		(body as Unit).take_hit(5)

You can add @icon("res://icons/knight.svg") above class_name to give the node type a custom icon in the editor. Use class_name for types other code refers to (units, items, resources, components); one-off scripts like a level's main.gd don't need it, and every global name is one more thing that can clash.

Inner classes, constructors, properties and super

class Name: inside a script declares an inner class, handy for small helper types. The runnable examples on this site use inner classes because each one is a single file. Everything about them also applies to file classes.

gdscript · try it yourself
extends SceneTree

class Unit:
	var name: String
	var max_hp := 20
	var hp: int:
		set(value):
			hp = clampi(value, 0, max_hp)   # every assignment goes through here
	var is_dead: bool:
		get: return hp == 0                 # computed, no storage of its own

	func _init(p_name: String, p_hp: int = 20) -> void:
		name = p_name
		max_hp = p_hp
		hp = p_hp

	func take_hit(amount: int) -> void:
		hp -= amount

	func describe() -> String:
		return "%s %d/%d" % [name, hp, max_hp]

	func _to_string() -> String:
		return "<Unit %s>" % name

class Knight extends Unit:
	var armor := 3

	func _init(p_name: String) -> void:
		super(p_name, 30)                   # call the parent constructor

	func take_hit(amount: int) -> void:
		super.take_hit(maxi(amount - armor, 0))

	func describe() -> String:
		return super() + " armor " + str(armor)

func _init():
	var slime := Unit.new("Slime", 12)
	var ser := Knight.new("Ser Ada")
	for u: Unit in [slime, ser]:
		u.take_hit(5)
		print(u.describe())
	slime.hp = 999
	print("set 999 -> ", slime.hp)
	slime.take_hit(100)
	print(slime, " dead? ", slime.is_dead)
	print(ser is Unit, " ", ser is Knight, " ", slime is Knight)
	quit()
Slime 7/12
Ser Ada 28/30 armor 3
set 999 -> 12
<Unit Slime> dead? true
true true false

What to notice:

  • _init() is the constructor; arguments passed to new() go to it. A node script that will be placed in a scene from the editor must be constructible without arguments, because the editor calls new() with none. Give parameters defaults or don't add any.
  • Setters and getters are written inline after the variable. Inside the setter, assigning hp writes the real value (it doesn't call the setter again). Setters run for assignments from inside the class too, which is what makes hp -= amount clamp.
  • super(...) calls the parent constructor, super.method() calls the parent version of an overridden method, and a bare super() inside a method calls the parent version of that method.
  • _to_string() controls what print() and str() show for your object.
  • Inner and file classes that don't say extends derive from RefCounted: they are freed automatically when the last reference goes away. Classes that extend Node or Object must be freed by you (nodes usually with queue_free()).

Enums, match and static members

gdscript · try it yourself
extends SceneTree

enum Element { FIRE, ICE, POISON = 10 }

class IdMaker:
	static var next_id := 1                 # one value shared by the whole class

	static func make(prefix: String) -> String:
		var id := "%s-%03d" % [prefix, next_id]
		next_id += 1
		return id

func weakness(e: Element) -> Element:
	match e:
		Element.FIRE:
			return Element.ICE
		Element.ICE:
			return Element.FIRE
		_:
			return Element.POISON

func _init():
	var e := Element.ICE
	print(e, " ", Element.keys()[e], " ", Element.POISON, " size ", Element.size())
	print("ICE is weak to ", Element.find_key(weakness(e)))
	for i in 3:
		print(IdMaker.make("orc"))
	print("next id: ", IdMaker.next_id)
	quit()
1 ICE 10 size 3
ICE is weak to FIRE
orc-001
orc-002
orc-003
next id: 4

A named enum is a dictionary-like type: its values are plain ints (ICE is 1), keys() lists the names, and find_key(value) turns a value back into its name. Typing a variable or parameter as Element makes the editor offer the right values, and an exported enum variable becomes a drop-down in the Inspector. static functions and variables belong to the class, not to an object, so IdMaker.make() works without new(). Static functions are perfect for small utility libraries (MathUtil.remap(...)).

Abstract classes (Godot 4.5+)

@abstract marks a class that can't be instantiated and methods that subclasses must implement. The editor reports a subclass that forgets one, and Pickup.new() is an error:

gdscript · try it yourself
extends SceneTree

@abstract class Pickup:
	var label: String
	@abstract func apply(stats: Dictionary) -> void

	func use(stats: Dictionary) -> void:
		apply(stats)
		print("used ", label, " -> ", stats)

class Coin extends Pickup:
	func _init() -> void: label = "coin"
	func apply(stats: Dictionary) -> void: stats.gold += 1

class Heart extends Pickup:
	func _init() -> void: label = "heart"
	func apply(stats: Dictionary) -> void: stats.hp = mini(stats.hp + 1, 3)

func _init():
	var stats := {"gold": 0, "hp": 2}
	var items: Array[Pickup] = [Coin.new(), Heart.new(), Heart.new()]
	for it in items:
		it.use(stats)
	quit()
used coin -> { "gold": 1, "hp": 2 }
used heart -> { "gold": 1, "hp": 3 }
used heart -> { "gold": 1, "hp": 3 }

In a file class, put @abstract on the line before class_name. Before 4.5, the convention was a base method that calls push_error("not implemented").

Note: Deep inheritance trees (Entity > Character > Enemy > FlyingEnemy > Boss) get hard to change. In Godot, prefer small scenes and child nodes that each do one job (a Health node, a Hitbox node) and keep inheritance shallow. Field Notes: Scene Architecture shows why.

Test yourself

What does class_name Knight at the top of a script do?

  1. Renames the node in the scene
  2. Registers Knight as a global type usable in type hints, is checks and the Create Node dialog
  3. Makes the class abstract
  4. Creates an autoload

Inside Knight.take_hit, what does super.take_hit(n) call?

  1. Knight.take_hit again (recursion)
  2. The parent class's take_hit
  3. The first child node's take_hit
  4. The static version of the method

Why must a node script used in the editor be constructible with new() and no arguments?

  1. GDScript doesn't support constructor arguments
  2. The editor and scene loading create the node by calling new() without arguments
  3. Arguments make the node static
  4. Nodes can't have _init