Anwendung objektorientierter Prinzipien in Godot

The engine offers two main ways to create reusable objects: scripts and scenes. Neither of these technically define classes under the hood.

Bei vielen Best Practices mit Godot werden jedoch objektorientierte Programmierprinzipien auf die Skripte und Szenen angewendet, aus denen Ihr Spiel besteht. Deshalb ist es nützlich zu verstehen, wie wir sie als Klassen betrachten können.

This guide briefly explains how scripts and scenes work in the engine's core to help you understand how they work under the hood.

How scripts work in the engine

The engine provides built-in classes like Node. You can extend those to create derived types using a script.

These scripts are not technically classes. Instead, they are resources that tell the engine a sequence of initializations to perform on one of the engine's built-in classes.

Godot's internal classes have methods that register a class's data with a ClassDB. This database provides runtime access to class information. ClassDB contains information about classes like:

  • Eigenschaften
  • Methods.
  • Konstanten
  • Signale

This ClassDB is what objects check against when performing an operation like accessing a property or calling a method. It checks the database's records and the object's base types' records to see if the object supports the operation.

Attaching a Script to your object extends the methods, properties, and signals available from the ClassDB.

Bemerkung

Even scripts that don't use the extends keyword implicitly inherit from the engine's base Reference class. As a result, you can instantiate scripts without the extends keyword from code. Since they extend Reference though, you cannot attach them to a Node.

Szenen

The behavior of scenes has many similarities to classes, so it can make sense to think of a scene as a class. Scenes are reusable, instantiable, and inheritable groups of nodes. Creating a scene is similar to having a script that creates nodes and adds them as children using add_child().

We often pair a scene with a scripted root node that makes use of the scene's nodes. As such, the scene is often an extension of the script's declarative code.

The content of a scene helps to define:

  • Welche Nodes sind dem Skript verfügbar
  • Wie sie organisiert sind
  • Wie sie initialisiert werden
  • What signal connections they have with each other

Warum ist irgendetwas davon für die Organisation der Szene wichtig? Weil Instanzen von Szenen Objekte sind. Infolgedessen gelten viele objektorientierte Prinzipien, die für geschriebenen Code gelten, auch für Szenen: Einzelverantwortung, Kapselung und andere.

The scene is always an extension of the script attached to its root node, so you can interpret it as part of a class.

Most of the techniques explained in this best practices series build on this point.