GDScript classes
GDScript Classes
GDScript is a scripting language used in the Godot game engine. It is designed to be easy to learn and use, especially for beginners in game development. GDScript supports object-oriented programming, and classes are an essential part of organizing and structuring code in GDScript.
Classes in GDScript are used to define objects with specific properties and behaviors. They serve as blueprints or templates for creating instances of objects. Each class can have variables (called properties) and functions (called methods) associated with it.
To define a class in GDScript, you use the class
keyword followed by the class name. Here's an example of a simple GDScript class:
class Player:
var name: String
var health: int
func takeDamage(damage: int):
health -= damage
func heal(amount: int):
health += amount
In the above example, we define a Player
class with two properties (name
and health
) and two methods (takeDamage
and heal
). The var
keyword is used to declare variables, and the func
keyword is used to define functions.
To create an instance of a class, you use the new
keyword followed by the class name. Here's an example:
var player = Player.new()
player.name = "John"
player.health = 100
In the above example, we create a new instance of the Player
class and assign it to the player
variable. We can then access and modify the properties of the player
object.
Classes in GDScript can also inherit from other classes to inherit their properties and methods. This allows for code reuse and the creation of more specialized classes. Inheritance is achieved using the extends
keyword. Here's an example:
class Enemy extends Character:
func attack(target: Character):
target.takeDamage(10)
In the above example, the Enemy
class inherits from a hypothetical Character
class and adds its own attack
method.
That's a brief overview of GDScript classes. They are a fundamental part of organizing and structuring code in GDScript, allowing for code reuse and modularity.