Introduction

GDScript is a high-level, dynamically typed programming language used to create content within the Godot Engine. It is designed to be easy to learn and use.

Basic Syntax

# Single line comment
var x = 10  # Variable declaration
if x > 5:
    print("x is greater than 5")
                

Variables and Types

var my_int: int = 42
var my_float: float = 3.14
var my_string: String = "Hello, Godot!"
                

Functions

func my_function(param1: int) -> int:
    return param1 * 2
                

Classes and Inheritance

class_name MyClass
extends Node

func _ready():
    print("Hello from MyClass")
                

Signals

signal my_signal

func _ready():
    emit_signal("my_signal")
                

Examples

# Example of a simple script
extends Sprite

func _ready():
    print("Sprite is ready")
                

System Functions

GDScript provides several built-in functions that are called automatically by the engine. Here are the system functions and the order in which they run:


# Called when the script instance is created.
func _init():
    print("Script instance created")

# Called when the node is added to the scene.
func _enter_tree():
    print("Node entered the scene tree")

# Called when the node is fully initialized.
func _ready():
    print("Node is ready")

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    print("Processing frame")

# Called every physics frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
    print("Processing physics frame")

# Called when an input event is received.
func _input(event):
    print("Input event received")

# Called when an input event is received and not handled by any node.
func _unhandled_input(event):
    print("Unhandled input event received")

# Called when a key input event is received and not handled by any node.
func _unhandled_key_input(event):
    print("Unhandled key input event received")

# Called for various notifications.
func _notification(what):
    print("Notification received:", what)

# Called when the node is about to be removed from the scene tree.
func _exit_tree():
    print("Node exited the scene tree")

# Called when the node is about to be deleted.
func _finalize():
    print("Node is about to be deleted")
                
Order of execution:
  1. _init()
  2. _enter_tree()
  3. _ready()
  4. _process(delta) and _physics_process(delta) (called every frame)
  5. _input(event), _unhandled_input(event), and _unhandled_key_input(event) (called on input events)
  6. _notification(what) (called on notifications)
  7. _exit_tree()
  8. _finalize()

Creating and Using Timers

# Create a new Timer node
var timer = Timer.new()
timer.wait_time = 2.0
timer.one_shot = false
timer.connect("timeout", self, "_on_timer_timeout")
add_child(timer)
timer.start()

# Function to be called when the timer times out
func _on_timer_timeout():
    print("Timer timed out")
                

Alternatively, you can add a Timer node directly in the scene tree and configure it in the editor. Then, connect its timeout signal to a function:


# In the editor, add a Timer node and name it "MyTimer"
# Connect the timeout signal to this function
func _on_MyTimer_timeout():
    print("MyTimer timed out")

# Start the timer in code
$MyTimer.start()
                

Using Tweens

# Create a new Tween node
var tween = Tween.new()
add_child(tween)
tween.tween_property(self, "position", Vector2(100, 100), 1.0, Tween.TRANS_LINEAR, Tween.EASE_IN_OUT)
tween.connect("tween_completed", self, "_on_tween_completed")

# Function to be called when the tween completes
func _on_tween_completed(object, key):
    print("Tween completed for", object, "property", key)
                

Alternatively, you can add a Tween node directly in the scene tree and configure it in the editor. Then, start the tween in code:


# In the editor, add a Tween node and name it "MyTween"
# Start the tween in code
$MyTween.tween_property(self, "position", Vector2(100, 100), 1.0, Tween.TRANS_LINEAR, Tween.EASE_IN_OUT)
$MyTween.connect("tween_completed", self, "_on_tween_completed")

# Function to be called when the tween completes
func _on_tween_completed(object, key):
    print("Tween completed for", object, "property", key)
                

Opening and Reading Files

# Create a new File object
var file = File.new()
if file.open("res://path/to/your/file.txt", File.READ) == OK:
    var content = file.get_as_text()
    print(content)
    file.close()
else:
    print("Failed to open the file")
                

You can also read the file line by line:


# Create a new File object
var file = File.new()
if file.open("res://path/to/your/file.txt", File.READ) == OK:
    while not file.eof_reached():
        var line = file.get_line()
        print(line)
    file.close()
else:
    print("Failed to open the file")
                

Opening and Reading JSON Files

# Create a new File object
var file = File.new()
if file.open("res://path/to/your/file.json", File.READ) == OK:
    var content = file.get_as_text()
    var json_data = JSON.parse(content)
    if json_data.error == OK:
        var data = json_data.result
        print(data)
    else:
        print("Failed to parse JSON:", json_data.error_string)
    file.close()
else:
    print("Failed to open the file")
                

Example JSON file content:


{
    "name": "Godot",
    "version": 4.3,
    "features": ["2D", "3D", "GDScript"]
}
                

Using Groups

# Adding a node to a group
func _ready():
    add_to_group("my_group")

# Removing a node from a group
func _exit_tree():
    remove_from_group("my_group")

# Performing an action on all nodes in a group
func perform_action_on_group():
    var group_nodes = get_tree().get_nodes_in_group("my_group")
    for node in group_nodes:
        node.perform_action()

# Example function to be called on each node in the group
func perform_action():
    print("Action performed on", self.name)
                

Groups can be managed in the editor as well. You can add or remove nodes from groups using the "Groups" tab in the node inspector.


Operators Arithmetic Operators

# Addition
var sum = 5 + 3  # 8

# Subtraction
var difference = 5 - 3  # 2

# Multiplication
var product = 5 * 3  # 15

# Division
var quotient = 5 / 3  # 1.6667

# Modulus
var remainder = 5 % 3  # 2
                
Comparison Operators

# Equal to
var is_equal = (5 == 3)  # false

# Not equal to
var is_not_equal = (5 != 3)  # true

# Greater than
var is_greater = (5 > 3)  # true

# Less than
var is_less = (5 < 3)  # false

# Greater than or equal to
var is_greater_or_equal = (5 >= 3)  # true

# Less than or equal to
var is_less_or_equal = (5 <= 3)  # false
                
Logical Operators

# Logical AND
var and_result = (true and false)  # false

# Logical OR
var or_result = (true or false)  # true

# Logical NOT
var not_result = not true  # false
                
Assignment Operators

# Assignment
var x = 5

# Addition assignment
x += 3  # x is now 8

# Subtraction assignment
x -= 3  # x is now 5

# Multiplication assignment
x *= 3  # x is now 15

# Division assignment
x /= 3  # x is now 5

# Modulus assignment
x %= 3  # x is now 2
                
Bitwise Operators

# Bitwise AND
var and_bitwise = 5 & 3  # 1

# Bitwise OR
var or_bitwise = 5 | 3  # 7

# Bitwise XOR
var xor_bitwise = 5 ^ 3  # 6

# Bitwise NOT
var not_bitwise = ~5  # -6

# Bitwise left shift
var left_shift = 5 << 1  # 10

# Bitwise right shift
var right_shift = 5 >> 1  # 2