What is the best programming language for Godot?
With the release of Godot 4, more developers than ever before are flocking to learn this free and open-source engine. However, many come in not knowing what programming language they need to use. While C# is an option (for those familiar with Unity), GDScript is by far the go-to when it comes to scripting in Godot.
What is GDScript, though, and how does it work? In this article, we’re going to cover the fundamentals of GDScript so you can start tackling your Godot game projects with finesse.
If you’re ready, let’s get started!
Introduction to GDScript
Welcome to the world of GDScript! In this section, you’ll learn what GDScript is, why you should use it, and how to set up your development environment so you can start writing code right away.
What is GDScript?
GDScript is a scripting language that was specifically designed for the game engine Godot. It’s a high-level language, which means it’s easy to read and write compared to lower-level languages like C++. And best of all, it’s designed with game development in mind, so it has features that make game development faster and easier.
Benefits of using GDScript
Here are a few reasons why GDScript is a great choice for game development:
- It’s easy to learn and use, even for those who are new to programming
- It’s optimized for game development, so you can write code faster and more efficiently
- It integrates well with the Godot engine, making it a great choice for game development with Godot
Setting up the development environment
To start using GDScript, you’ll need to download and install the Godot game engine. You can download it for free from the Godot website. Once you have Godot installed, you’re ready to start writing GDScript code!
In the next section, we’ll dive into the basics of GDScript and start writing some code. Let’s get started!
Variables and Data Types
In this section, you’ll learn how to store and manipulate data in GDScript. You’ll learn about variables and different data types, and how to declare and initialize them.
Introduction to Variables
Variables are containers that store values in your code. Think of them like little containers that hold data that you can use and manipulate in your code. For example, you can store a player’s name in a variable so that you can use it throughout your game.
Declaring and Initializing Variables
To use a variable, you first have to declare it. You do this by giving it a name and specifying what type of data it will store. Here’s an example of declaring a variable in GDScript:
var player_name: String
In this example, we declared a variable named “player_name” that will store a string value. To initialize a variable, you give it a value when you declare it like this:
var player_name: String = "John Doe"
Data Types in GDScript
In GDScript, there are several data types that you can use to store different types of data. Here are the most common data types in GDScript:
- Integer: Whole numbers, such as 1, 2, 3, etc.
var score: int = 10
- Float: Numbers with decimal places, such as 1.5, 2.7, etc.
var price: float = 19.99
- String: Text values, such as “hello”, “goodbye”, etc.
var player_name: String = "John Doe"
- Boolean: A value that can either be “true” or “false”.
var game_over: bool = false
- Array: A collection of values that can be of any data type.
var players: Array = [ "John Doe", "Jane Doe", "Jim Doe" ]
- Dictionary: A collection of key-value pairs where each key is unique.
var player_scores: Dictionary = { "John Doe": 10, "Jane Doe": 20, "Jim Doe": 30 }
In the next section, we’ll learn about operators and expressions, which are used to manipulate data in your code.
Operators and Expressions
In this section, you’ll learn how to perform operations and manipulate data using operators and expressions in GDScript. We’ll cover different types of operators and how to use them in your code.
Arithmetic Operators
Arithmetic operators are used to perform basic arithmetic operations like addition, subtraction, multiplication, division, and more. Here are the most common arithmetic operators in GDScript:
- +: Addition operator, used to add two values together.
var result = 2 + 2 # result will be 4
- -: Subtraction operator, used to subtract one value from another.
var result = 5 - 2 # result will be 3
- *: Multiplication operator, used to multiply two values.
var result = 2 * 2 # result will be 4
- /: Division operator, used to divide one value by another.
var result = 4 / 2 # result will be 2
- %: Modulus operator, used to find the remainder of a division operation.
var result = 7 % 3 # result will be 1
Assignment Operators
Assignment operators are used to assign values to variables. Here are the most common assignment operators in GDScript:
- =: Simple assignment operator, used to assign a value to a variable.
var score = 10
- +=: Addition assignment operator, used to add a value to a variable and then assign the result back to the same variable.
var score = 10 score += 5 # score will now be 15
- -=: Subtraction assignment operator, used to subtract a value from a variable and then assign the result back to the same variable.
var score = 10 score -= 5 # score will now be 5
- *=: Multiplication assignment operator, used to multiply a value with a variable and then assign the result back to the same variable.
var score = 10 score *= 2 # score will now be 20
- /=: Division assignment operator, used to divide a value with a variable and then assign the result back to the same variable.
var score = 10 score /= 2 # score will now be 5
Comparison Operators
Comparison operators are used to compare two values and return a boolean value based on the comparison result. Here are the most common comparison operators in GDScript:
- ==: Equality operator, used to check if two values are equal.
var result = 2 == 2 # result will be true
- !=: Inequality operator, used to check if two values are not equal.
var result = 2 != 2 # result will be false
- <: Less than operator, used to check if one value is less than another.
var result = 2 < 3 # result will be true
- >: Greater than operator, used to check if one value is greater than another.
var result = 2 > 3 # result will be false
- <=: Less than or equal to operator, used to check if one value is less than or equal to another.
var result = 2 <= 2 # result will be true
- >=: Greater than or equal to operator, used to check if one value is greater than or equal to another.
var result = 2 >= 3 # result will be false
Logical Operators
Logical operators are used to perform operations on boolean values and return a boolean result. Here are the most common logical operators in GDScript:
- and: Logical and operator, used to combine two boolean values and returns true only if both values are true.
var result = true and true # result will be true
- or: Logical or operator, used to combine two boolean values and returns true if at least one value is true.
var result = false or true # result will be true
- not: Logical not operator, used to negate a boolean value and returns the opposite value.
var result = not false # result will be true
Control Flow Statements
Control flow statements allow you to control the flow of execution of your code based on certain conditions. Here are the most common control flow statements in GDScript.
If Statement
The if statement allows you to execute a block of code only if a certain condition is met. Here’s an example:
if 2 > 1: print("2 is greater than 1") # Output: 2 is greater than 1
If-Else Statement
The if-else statement allows you to execute a block of code if a certain condition is met, and another block of code if the condition is not met. Here’s an example:
if 2 < 1: print("2 is less than 1") else: print("2 is not less than 1") # Output: 2 is not less than 1
For Loop
The for loop allows you to execute a block of code repeatedly for a specific number of times. Here’s an example:
for i in range(3): print(i) # Output: # 0 # 1 # 2
While Loop
The while loop allows you to execute a block of code repeatedly as long as a certain condition is met. Here’s an example:
i = 0 while i < 3: print(i) i += 1 # Output: # 0 # 1 # 2
Functions
Functions allow you to group a set of related code together and reuse it whenever you need it. Functions make your code more organized and readable. Here’s how to define and use functions in GDScript.
Defining Functions
You can define a function using the “func” keyword, followed by the function name, a list of parameters in parenthesis, and a block of code inside curly braces. Here’s an example:
func greet(name): print("Hello, " + name) greet("John") # Output: Hello, John
Return Statement
The return statement allows you to return a value from a function. Here’s an example:
func square(x): return x * x result = square(3) print(result) # Output: 9
Optional Parameters
You can specify default values for parameters in case they are not provided when the function is called. Here’s an example:
func greet(name, greeting="Hello"): print(greeting + ", " + name) greet("John") # Output: Hello, John greet("Jane", "Hi") # Output: Hi, Jane
Variable Number of Parameters
You can accept a variable number of parameters by using the “*args” syntax. Here’s an example:
func sum(*numbers): result = 0 for number in numbers: result += number return result print(sum(1, 2, 3, 4)) # Output: 10
Classes and Objects
Classes and objects are fundamental concepts in object-oriented programming (OOP). They allow you to create complex data structures and provide a way to encapsulate data and behavior. Here’s how to use classes and objects in GDScript.
Defining Classes
You can define a class using the “class” keyword, followed by the class name and a block of code inside curly braces. Here’s an example:
class Person: var name func greet(): print("Hello, my name is " + name) person = Person.new() person.name = "John" person.greet() # Output: Hello, my name is John
Constructor
The constructor is a special method that is automatically called when an object is created from a class. You can use the constructor to initialize the object’s properties. Here’s an example:
class Person: var name func _init(name): self.name = name func greet(): print("Hello, my name is " + name) person = Person.new("John") person.greet() # Output: Hello, my name is John
Inheritance
Inheritance allows you to create a new class that is a derived version of an existing class. The derived class inherits all the properties and methods of the base class. Here’s an example:
class Employee(Person): var company func work(): print(name + " is working at " + company) employee = Employee.new("Jane") employee.name = "Jane" employee.company = "Acme Inc." employee.greet() employee.work() # Output: # Hello, my name is Jane # Jane is working at Acme Inc.
Polymorphism
Polymorphism allows you to use an object of a derived class anywhere an object of the base class can be used, because the derived class is considered a subclass of the base class. Here’s an example:
func introduce(person): person.greet() introduce(person) introduce(employee) # Output: # Hello, my name is John # Hello, my name is Jane
Error Handling
Error handling is an important aspect of programming. It allows you to gracefully handle unexpected situations and prevent your program from crashing. Here’s how to handle errors in GDScript.
Try-Except Blocks
The try-except block allows you to wrap a block of code that might raise an exception, and handle the exception if it does. Here’s an example:
try: # code that might raise an exception print(1 / 0) except DivisionByZero: # code to handle the exception print("Cannot divide by zero.") # Output: Cannot divide by zero.
Raising Exceptions
You can raise an exception explicitly using the “raise” keyword, followed by an exception object. This allows you to signal that something unexpected has happened and stop the execution of the current function. Here’s an example:
func divide(a, b): if b == 0: raise ValueError("Cannot divide by zero.") return a / b try: result = divide(10, 0) print(result) except ValueError as error: print(error) # Output: Cannot divide by zero.
Custom Exceptions
You can create your own custom exception classes to signal specific error conditions. Here’s an example:
class DivisionByZeroError(Exception): pass func divide(a, b): if b == 0: raise DivisionByZeroError("Cannot divide by zero.") return a / b try: result = divide(10, 0) print(result) except DivisionByZeroError as error: print(error) # Output: Cannot divide by zero.
File Input and Output
In this section, you’ll learn how to read from and write to files in GDScript. This is useful for storing data that you want to persist across multiple runs of your program.
Writing to Files
You can write to files using the “File” class in GDScript. Here’s an example that writes a message to a file:
var file = File.new() file.open("message.txt", File.WRITE) file.store_string("Hello, world!") file.close()
In this example, we create a new “File” object, open a file named “message.txt” for writing, store the string “Hello, world!” in the file, and then close the file. If the file doesn’t exist, it will be created. If it does exist, its contents will be overwritten.
Reading from Files
You can read from files using the “File” class in GDScript. Here’s an example that reads a message from a file:
var file = File.new() file.open("message.txt", File.READ) var message = file.get_as_text() file.close() print(message) # Output: Hello, world!
In this example, we create a new “File” object, open a file named “message.txt” for reading, retrieve the contents of the file as a string, and then close the file. We then print the contents of the file to the console.
Error Handling
When working with files, it’s important to handle errors that might occur, such as trying to open a file that doesn’t exist or trying to read from a file that hasn’t been opened for reading. Here’s an example that demonstrates error handling:
var file = File.new() try: file.open("nonexistent.txt", File.READ) except Error: print("Cannot open file.") finally: file.close() # Output: Cannot open file.
In this example, we create a new “File” object and attempt to open a file named “nonexistent.txt” for reading. If the file doesn’t exist, an “Error” exception will be raised and caught by the “except” block. We print an error message and then close the file in the “finally” block, which will be executed regardless of whether an exception was raised or not.
Conclusion
Congratulations, you’ve now learned the basics of GDScript! You can use this knowledge to create your own games and applications in Godot Engine.
However, there is more to learn than just GDScript. Godot offers a ton of fantastic features and tools – from simple tilemap painters to performant rendering options. Plus, these coding principles – while important – aren’t of any use unless you learn how to apply them practically to game projects.
To end this article, we’ve included a bunch of helpful resources below to help you get started on the next steps in your Godot journey. We hope this helps, and we’re looking forward to seeing what you do with Godot 4!
Primary Resources
Premium Godot Tutorials
- Godot 4 Game Development Mini-Degree by Zenva
- Godot 3 Game Development Mini-Degree by Zenva
Free Godot Tutorials
- Godot 101 – Game Engine Foundations by Zenva
- COMPLETE COURSE – Learn the GODOT Game Engine in 50 MINUTES by Zenva
- Godot Basics Tutorial Series by Godot Tutorials
- GDScript Fundamentals Tutorial Series by Godot Tutorials
- Godot Basics by CodeNMore
- *Complete* Godot Beginner Tutorial Series by Alvin Roe
- Godot 4 Crash Course for Beginners by Chris’ Tutorials
- Godot 4 for Beginners by A Dev Named Josh