Classes and Objects

Constructors

Constructors are special methods that are called when an object is initialized. In GDScript, the constructor is named _init:

class MyClass:
    func _init():
        print("Object initialized!")

Inheritance

Inheritance is a way for one class to inherit the properties and methods of another class. To inherit from another class, use the extends keyword:

# Derived class
class_name DerivedClass extends MyBaseClass

func my_method():
    print("Hello from the derived class!")

Methods

Methods are functions that belong to a class or an object. They can be used to perform actions or manipulate data:

class MyClass:
    func my_method():
        print("Hello, GDScript!")

Properties

Properties are variables that belong to a class or an object. They can be used to store data or state:

class MyClass:
    var my_property = 0

Creating Object

var player = Player.new()
player.name = "John Doe"
player.take_damage(50)

Defining Classes

To define a class, simply create a new script file (e.g., my_class.gd). The name of the file should represents the name of the class. Create a new file called player.gd with the following content:

class_name Player

var health: int = 100
var name: String = "Unnamed"

func take_damage(amount: int):
    health -= amount
    if health <= 0:
        print("Player", name, "has died!")
Comments