03.objects-types-and-classes

Objects, types, and classes

In this course, we have talked about objects, types, and the previously lesson mentioned classes with the class_name keyword.

They’re three terms you’ll often in programming discussions online.

They’re often presented abstractly, and they can be hard to grasp, so let’s try to demystify them.

Objects

In code, an object is a bundle of data (member variables) and functions.

It’s completely different from objects in the real world: you can think of objects on the computer as little machines that do stuff.

For example, in Godot, a Sprite displays a texture somewhere on the screen. That Sprite is an object.

An Area2D detects physics bodies and has properties to filter what it sees. It’s also an object. The CollisionShape2D it needs as a child is another object.

Actually, every node or resource you create in Godot is an object because they’re all bundles of data and functions.

Types

Every object has a corresponding type.

A type is a name we use to specify what values are valid. Similar to how web forms only accept certain types of input, types tell the computer which values to accept or reject.

For example, on a website, a phone form field would accept phone numbers but reject letters.

In GDScript, a function that accepts the type Node2D would accept an Area2D but reject an int or an Array.

Why is the type Area2D compatible with Node2D? Because Area2D extends Node2D. It has all the member variables and functions from Node2D and more.

We say that an Area2D is a Node2D, which is a Node because Area2D extends the type Node2D, which extends Node.

Classes

In GDScript, you create objects from classes.

A class is a blueprint: a recipe that Godot can use to create more objects of a given type.

For example, the class Node2D contains the recipe to create Node2D nodes. Your CharacterStats script from the previous lesson was a recipe to make new CharacterStats resources.

Every script defines a class in GDScript. One way to think of it is that a class is a factory from which you make little machines we call objects.

For example, when you write Label.new(), you create a label object from the Label class.

To summarize, Godot uses recipes called classes to create objects of a certain type.

Don’t worry too much if it doesn’t click right now. These concepts are abstract and can take time to wrap your head around.

In the next lesson, we will use a resource to allow two players to move simultaneously with different controls.