Gdscript Class Tutorial – Complete Guide

Welcome to this tutorial, where we’ll explore the world of GDScript class – a key component of Godot’s scripting language. It’s a journey that will take us from understanding the core concepts of classes to getting our hands dirty with engaging and practical examples. So sit tight and let’s dive into this exciting topic!

What are GDScript Classes?

Very simply, a GDScript class can be thought of as a blueprint for creating objects – it instructs the game engine on how to construct an object, defining its properties and behaviors. These classes are critical to organize and structure your code in Godot, ensuring both scalability and maintainability.

What are GDScript Classes used for?

GDScript classes facilitate the creation of multiple objects of the same type. Each object is an instance of a class, carrying its own set of property values. This becomes incredibly useful when you want multiple game entities sharing similar behaviors but differ in certain characteristics, like enemies with varying health points or weapons with different fire rates.

Why should I learn about GDScript Classes?

Learning about GDScript classes not only enhances your Godot programming skills, but also opens up a dimension of streamlined game development. By using classes, you ensure your code is organized, recycle-able and easy to debug, all of which are crucial for efficient game development. So, let’s equip ourselves with this powerful tool and take our game creation journey to the next level!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Defining a GDScript Class

Defining a class in GDScript is a breeze. Let’s create a class for a video game character.

class_name Character
var name
var hit_points
var weapon

In this example, our ‘Character’ class has three properties: ‘name’, ‘hit_points’, and ‘weapon’.

Creating Instances of a GDScript Class

Now that we’ve defined a class, let’s put it to use by creating an instance.

var hero = Character.new()
hero.name = "Zenva Knight"
hero.hit_points = 100
hero.weapon = "Sword"

Here, we create a new ‘Character’ instance called ‘hero’ and set its properties accordingly.

Methods in GDScript Classes

Classes are not only about properties, they also encapsulate behaviors in the form of ‘methods’.

class_name Character
var name
var hit_points
var weapon

func talk():
    print("Hello, I am " + name)

The ‘talk’ method allows our character to introduce itself.

var hero = Character.new()
hero.name = "Zenva Knight"
hero.talk()  
# Output: Hello, I am Zenva Knight

By calling ‘hero.talk()’, our ‘Zenva Knight’ character greets us.

Creating a GDScript Subclass

Subclasses allow us to organize similar kinds of objects. They inherit all properties and methods from their ‘superclass’.

class_name Villain extends Character

func threaten():
    print("I am " + name + ". Prepare to be defeated!")

Our ‘Villain’ class extends ‘Character’, inheriting all its properties and methods, and also adds a new method ‘threaten’.

var enemy = Villain.new()
enemy.name = "Evil Wizard"
enemy.threaten()  
# Output: I am Evil Wizard. Prepare to be defeated!

By calling ‘enemy.threaten()’, our ‘Evil Wizard’ character threatens us! He can also ‘talk()’ because he is a subclass of ‘Character’.

Exploiting Inheritance in GDScript Classes

Beyond straightforward subclassing, GDScript also allows us to override methods from the superclass. This is a powerful tool that enables us to modify behaviors in subclasses without changing the original class. Here’s how we override the ‘talk’ method in our ‘Villain’ class.

class_name Villain extends Character

func threaten():
    print("I am " + name + ". Prepare to be defeated!")

func talk():
    print("I am " + name + ". You cannot beat me!")

Now, when we create a villain and call ‘talk()’, it boasts about its strength!

var enemy = Villain.new()
enemy.name = "Evil Wizard"
enemy.talk()  
# Output: I am Evil Wizard. You cannot beat me!

Intro to Class Variables and Class Methods

GDScript supports class variables and class methods – shared data and functionality that belong to the class itself and not to any specific instance. Let’s define a class variable in our ‘Character’ class to count how many characters have been created.

class_name Character
var name
var hit_points
var weapon
static var count = 0

func _init():
    count += 1

Every time we create a new character, ‘_init()’ gets called automatically and increases the count by 1.

var hero = Character.new()
hero.name = "Zenva Knight"
print(Character.count)  # Output: 1

var enemy = Villain.new()
enemy.name = "Evil Wizard"
print(Character.count)  # Output: 2

To manage class variables, we also define class methods. Let’s add a class method to reset the character count.

class_name Character
var name
var hit_points
var weapon
static var count = 0

func _init():
    count += 1

static func reset_count():
    count = 0

And we can call this method to reset the counter at any time.

Character.reset_count()
print(Character.count)  # Output: 0

With these new toolkit additions, we can better control our classes and make our game more dynamic and interactive!

Using Built-in Methods in GDScript Classes

Let’s start looking into some built-in methods that GDScript supports. These methods offer extra control and allow us to handle more advanced features. We’ll begin with the ‘_ready()’ method.

class_name Character
var name
var hit_points
var weapon

func _ready():
    print("A new character has been created!")

The ‘_ready()’ method is called automatically when a new instance of the class is added to the scene, letting us know that a new character has joined the game.

var hero = Character.new()
hero.name = "Zenva Knight"
# Output: A new character has been created!

Special Functions in GDScript Classes

We can also use some special functions to add physics-based behaviour to our classes, such as ‘_physics_process(delta)’ for handling motion and collisions.

class_name Character
var name
var hit_points
var weapon
var speed
var direction
var position

func _physics_process(delta):
    direction = get_input_direction()
    position += speed * direction * delta

This function is called during each physics frame and updates the position of the character based on its speed and direction. The ‘delta’ term is used to keep the motion smooth and frame rate independent.

Using Signals in GDScript Classes

GDScript also supports signals which are an excellent way of achieving inter-object communication. They allow objects to send notifications which other objects can listen and react to.

class_name Character
var name
var hit_points
var weapon

signal character_defeated

We’ve created a signal named ‘character_defeated’. Any object can now connect to this signal and perform an action whenever the signal is emitted.

func take_damage(amount):
    hit_points -= amount
    if hit_points <= 0:
        emit_signal('character_defeated')

The ‘character_defeated’ signal is emitted in the ‘take_damage’ function whenever the character’s hit points drop to zero or below.

Using methods, built-in functions, and signals we have equipped our characters with behaviours, reactions, and communication abilities, giving our games a new dimension of interactivity and dynamics! Keep exploring and innovating as you journey further into the world of GDScript classes!

Where to Go Next

Now you’ve gotten your feet wet with GDScript classes, the journey doesn’t end here. There’s so much more to explore and master in Godot and we at Zenva are here to guide you every step of the way.

Keep building your skills and diving deeper into the world of game development with our comprehensive Godot Game Development Mini-Degree. This broad collection of courses will allow you to build cross-platform games using Godot. Explore various topics including 2D and 3D assets, GDScript, gameplay control, combat mechanics, and UI systems. The curriculum even lets you work on your own projects, fortifying your portfolio with real Godot projects. Our courses cater to all skill levels, from beginners to more advanced learners.

If you’re looking for a more specific course or further exploration into Godot, we highly recommend you check out our full catalog of Godot Courses. These courses are designed to take you from a beginner to a professional game developer. At Zenva, we can’t wait to see what you’ll create next. Happy learning!

Conclusion

We hope this tutorial shed some light on the power of GDScript classes in Godot engine. With the foundational knowledge about classes, instances, methods, inheritance, and more, you’ve taken a major step into the world of game development.

Remember, every great game starts with a single line of code. So keep experimenting and expanding on the knowledge you’ve gained here. Try out our Godot Game Development Mini-Degree to further solidify your skills and bring your game ideas to life. Happy coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.