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!")
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 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 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 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
var player = Player.new()
player.name = "John Doe"
player.take_damage(50)
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!")