See all glossary terms

Inner Classes

Godot has two ways of creating new classes:
  1. Create a new script. Each script is a class by default (optionally named with the class_name keyword).
  2. Use the class keyword to create inner classes.
Here's an example of two inner classes:
class Person:
  var name := ""
  var age := 0

class Superhero extends Person:
  var power := ""
inner classes have some limitations compared to scripts: They cannot be initiated from the editor; so they can't be used for nodes and resources that you'd like to interact with in the editor (you can still use them in code).
However, they have some benefits too; for one, they keep multiple separated classes in the same file, which makes it easy to edit and read multiple related things.
Because their name isn't global, they also serve as a nice group for related functionality:
class_name Powers:

class _Power:
  var name := ""

class Flight extends _Power:
  var duration := 10

class Fireball extends _Power:
  var strength := 5
Now, anywhere in the project, you can call Powers.Flight.new() to create a new instance of Flight.
This grouping is typically called "namespacing" in most languages.
Another feature of inner classes is to create well typed objects that you only need for something specific.
Suppose I have a complicated function to get user properties for a connection:
func get_connect_properties() -> void:
  return {
    "user_name": "AzureDiamond"
    "password": "hunter2"
    "server_ip": "localhost"
    "port": 3000,
    "role": "moderator"
  }
This could be pretty annoying to use. Instead, I can do this:
class ConnectionProperties:
  user_name: String
  password: String
  server_ip: String
  port: number
  role: String

func get_connect_properties() -> void:
  var properties := ConnectionProperties.new()
  properties.user_name" = "AzureDiamond"
  properties.password" = "hunter2"
  properties.server_ip" = "localhost"
  properties.port" = 3000,
  properties.role" = "moderator"
  return properties
Now, when someone uses get_connect_properties(), they get a nice, well typed object.

See Also

Related terms in the Glossary