Menu

GDScript Inner Classes: class Inside a Script

Define small helper classes inside a GDScript file with the class keyword: instances, constructors, extending, reaching an inner class from another script, and what an inner class can and cannot see.

This page includes runnable editors. Edit, run, and see output instantly.

The class keyword defines a class inside a script. It is the right tool for small helper types that belong to one script:

[potion x3, key x1]
3

An inner class works like a file class: it has variables, methods, _init(), and it can be used as a type (Array[Slot], var s: Slot).

Extending Inside a File

An inner class may extend an engine class or another inner class:

9.00
3.14

What an Inner Class Can See

An inner class can use the outer script's constants, enums and other inner classes. It cannot use the outer script's member variables or methods, because an inner object is not tied to any outer object:

99 COMMON

Writing a member variable of the outer script inside Stack is a parse error: Identifier "player_name" not declared in the current scope. Pass the outer object in, for example func _init(owner_node: Node), when the inner class needs it.

Inner Classes Can Nest

1 room with 2 doors

Using an Inner Class from Another Script

Inner classes are reached through the outer class. With class_name Inventory in inventory.gd:

var slot := Inventory.Slot.new("arrow", 20)
var all_slots: Array[Inventory.Slot] = []

Without a class_name, preload the script first: const Inventory = preload("res://inventory.gd"), then Inventory.Slot.

Inner Class or Separate File?

Keep a class inner while it is small and only its outer script uses it. Move it to its own file with class_name when other scripts use it often, when it grows past a screen, or when it should be a node or resource type you can add in the editor.

Frequently Asked Questions

Can I have more than one class in a GDScript file?

Yes. The file itself is one class, and class Name: defines more classes inside it. Only the file's class can have a class_name; inner classes are reached through it, as in Inventory.Slot.

Does GDScript have structs?

No. The usual stand-ins are a small inner class with typed variables, a Dictionary, or a Resource when the data should be saved or edited in the Inspector.

Can an inner class use the outer class's variables?

It can use the outer class's constants, enums and other inner classes, but not its member variables or methods, because an inner class instance has no outer instance. Pass the outer object to the inner one if it needs it.

When should I move an inner class into its own file?

When other scripts use it a lot, when it grows past a screen of code, or when it should appear in the editor as a node or resource type. A separate file with class_name gives it a global name and an icon in the Create dialog.

Coddy programming languages illustration

Learn to code with Coddy

Get started