GDScript in Godot – Complete Guide

Welcome to the world of game development with Godot 4—the open-source game engine that’s taking the indie gaming community by storm. In this tutorial, we will dive into the powerful yet approachable language of Godot: GDScript. GDScript is a high-level, dynamically typed programming language that is especially designed for creating content within Godot. Whether you’re an absolute beginner eager to create your first game or an experienced coder looking to sharpen your skills, GDScript offers a blend of simplicity and efficiency that can bring your game ideas to life.

What is GDScript?

GDScript is a custom scripting language created for the Godot Engine. Its syntax closely mirrors that of Python, which means it’s incredibly readable and beginner-friendly. Despite this simplicity, it’s built to handle the complexity of game design with ease.

What is GDScript For?

GDScript is for scripting the behavior in games and applications made with Godot. It extends the functionality of objects within the engine, empowering developers with the tools necessary to animate characters, control physics, manage game states, and much more.

Why Should I Learn GDScript?

Learning GDScript is a compelling step for anyone looking to enter the field of game development. Its integration with Godot Engine allows for rapid development cycles, which is vital in an industry where being able to iterate quickly can make all the difference. Additionally, understanding GDScript lays a foundation in programming concepts that are translatable to other languages, broadening your professional toolkit.

CTA Small Image

Variables and Data Types in GDScript

GDScript boasts a variety of data types that are essential for game development. Let’s start by defining some variables.

var health = 100  # Integer
var name = "Player1"  # String
var is_alive = true  # Boolean
var speed = 4.5  # Float

To define a variable in GDScript, start with the keyword var followed by the variable’s name and an assigned value. GDScript is dynamically typed, but you can also use static typing if you prefer.

var score: int = 0  # Score with a static int type

Conditional Statements

Making decisions in a game is key. Conditional statements help control the flow of the game based on the conditions at play.

if health > 0:
    print("Player is alive")
elif health == 0:
    print("Player is knocked out")
    print("Player is deceased")

GDScript utilizes if, elif, and else for its control flow, just like Python.


Functions are blocks of code designed to perform a specific task. Here’s how to define a simple function to update the player’s score:

func update_score(amount):
    score += amount
    print("Score updated to: ", score)

Call a function simply by its name followed by parenthesis enclosing any arguments it requires.



Loops in GDScript allow you to repeat actions, which is quite useful for things like going through all enemies in a scene or accumulating damage.

For loops iterate over a range of numbers or through items in an array.

# For loop over a range
for i in range(5):
    print("This is loop iteration: ", i)

# For loop over an array
var enemies = ["Orc", "Goblin", "Dragon"]
for enemy in enemies:
    print("There is an enemy: ", enemy)

While loops continue as long as a condition is true.

var ammo_left = 10
while ammo_left > 0:
    print("There's ammo left! Shoot!")
    ammo_left -= 1  # Decrease ammo after each shot

These examples illustrate the basics of constructing the fundamental building blocks of GDScript, which form the backbone of the logic you will implement in a Godot game. As we proceed, you’ll see how these basics combine to form more complex game functionalities.Using signals is a great way to decouple your code. This mechanism allows objects to emit a ‘signal’ that other objects can listen for and respond to. Here’s a simple example in GDScript:

signal player_died

# To emit the signal somewhere in your code, use:

Connecting signals to methods can be done like this:

# Assuming you have an enemy object that emits a 'defeated' signal
enemy.connect("defeated", self, "_on_enemy_defeated")

# This is the method called when the signal is emmited
func _on_enemy_defeated():
    print("Enemy defeated!")

Arrays and dictionaries are essential in managing collections of data. Here’s a quick look at how they’re used in GDScript:

# An array of scores
var scores = [450, 200, 85, 920]

# Accessing elements
print(scores[0])  # Outputs: 450

# Adding a new element

# A dictionary stores key-value pairs.
var player_stats = {
    "health": 100,
    "magic": 40,
    "strength": 15

# Accessing values by keys
print(player_stats["health"])  # Outputs: 100

# Adding a new key-value pair
player_stats["agility"] = 12

Error handling in GDScript can be managed using the try-catch-finally construct, similar to exceptions in other languages. Here’s how you handle exceptions:

func dangerous_function():
    if randf() > 0.5:  # random float number between 0.0 and 1.0
        raise("Something went wrong!")

func example():
    catch error:
        print("Caught an error: ", error)
        print("This gets executed no matter what")

Implementing Inheritance can help you create more organized and maintainable code. Suppose you have a base class for all characters in your game:

extends Node

class_name Character
var health = 100
var strength = 10

func take_damage(amount):
    health -= amount

You can then create a subclass, inheriting properties and methods from the base class:

extends Character

class_name Enemy

var aggression_level = 3

func attack(target):
    target.take_damage(strength * aggression_level)

By mastering these features of GDScript and the fundamentals shown earlier, you will have a solid foundation for scriptwriting in Godot 4. Each code snippet here serves as a stepping stone for developing more intricate game mechanics. As our game evolves, we can combine these building blocks in creative ways to develop unique gameplay experiences. Remember, game development is not just about coding but also about bringing together art, sound, and interactivity into a cohesive whole. With GDScript and Godot at your fingertips, you’re well on your way to doing just that.As we delve deeper into GDScript, understanding object-oriented principles is crucial. Godot’s nodes are akin to objects, and your scripts typically extend these nodes to enhance their behavior.

Let’s explore inheritance further by creating a player class:

extends Character

class_name Player

var experience = 0

func gain_experience(amount):
    experience += amount

In this snippet, a Player class is created with an experience property and a method to increase it. Since it extends the Character class, it also inherits the properties and methods from Character, like health and take_damage.

Now, let’s look at how to override a parent method:

func take_damage(amount):
    .take_damage(amount)  # Calls the parent method
    print("Player took damage and now has ", health, " health left.")

By using the dot (.) before the method name, we call the parent’s version of the method before extending its functionality.

Next, consider an inventory system. Godot allows you to create custom classes for a more robust design:

class Item:
    var name = "Unknown"
    var description = ""
    var quantity = 0

    func _init(_name, _description, _quantity):
        name = _name
        description = _description
        quantity = _quantity

You can instantiate this class and create an inventory array for your player:

var player_inventory = []

player_inventory.append("Potion", "Restores health.", 3))
player_inventory.append("Elixir", "Restores magic.", 1))

# Let's count how many potions we have.
var potion_count = 0
for item in player_inventory:
    if == "Potion":
        potion_count += item.quantity
print("Total Potions: ", potion_count)

To manage custom signals and instances, suppose you want characters to notify others when they’re hit. Let’s create a signal in the Character class and emit it upon taking damage:

signal character_hit(character)

func take_damage(amount):
    health -= amount
    emit_signal("character_hit", self)

Any other object interested in when a character is hit can connect to that signal:

func _ready():
    # Connect the character_hit signal from each character in the game
    for character in characters:
        character.connect("character_hit", self, "_on_character_hit")

func _on_character_hit(hit_character):
    print(, " has been hit!")

Finally, interacting with the Godot editor from code is possible when you need to create tool scripts. Here’s a simplification of a tool script:

tool  # Makes the script run in the editor
extends Sprite

export (Texture) var custom_texture setget set_texture

func set_texture(value):
    texture = value
    if Engine.is_editor_hint():  # Check if we're in the editor
        update()  # Update the Sprite in the editor

Combining these code examples exemplifies the versatility and power of GDScript. From defining classes and making the most of inheritance to creating custom signals for robust inter-object communication, these coding mechanisms are your paint and brush in the canvas that is game development with Godot 4. Each new script, function, or signal you create adds another layer of interaction and complexity to the worlds you are building. It’s this exciting combination of creativity and technical skills that makes game development with GDScript an enjoyable and rewarding experience.

Where to go next on your Godot Journey

If the world of GDScript and Godot has sparked your interest, your journey into game development has just begun. To continue honing your skills and building your knowledge, we invite you to check out our Godot Game Development Mini-Degree. This comprehensive program is structured to take you from the basics to more advanced concepts, ensuring a learning path that grows with you.

Whether you’re a beginner with no prior coding experience or looking to solidify and expand your existing game development expertise, our curated courses have you covered. You’ll dive into creating cross-platform games using detailed instructions and hands-on practice. From understanding 2D and 3D assets to mastering gameplay control flow and various game mechanics, our Godot Mini-Degree is your gateway to becoming proficient with the Godot Engine.

And for those who are interested in exploring a broader range of topics within Godot, we have a full collection of Godot courses designed to empower your learning and development in this powerful engine. Start your journey with Zenva today, build a strong portfolio, and take a confident step into the game development industry.


In your hands lies the power to turn visions into interactive reality. GDScript and Godot 4 offer simplicity and depth, ideal for aspiring game creators and seasoned developers alike. The path ahead is filled with learning and creativity, and every line of code leads to the next milestone in your game development career. Embrace the journey, unleash your potential, and let your creations captivate players around the world.

Remember that we at Zenva are here to guide you every step of the way. Continue your adventure in game creation with our Godot Game Development Mini-Degree, a treasure trove of knowledge and resources awaiting your discovery. There’s no better time than now to start crafting your dream games – let’s code, create, and connect through the exciting realm of Godot!

Python Blog Image

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