GDScript is Godot’s built-in, high-level scripting language designed specifically for game development. It features a Python-like syntax that’s easy to learn while being tightly integrated with the Godot Engine.
GDScript is gradually typed, meaning type hints are optional but recommended for better performance and safety.
# Basic functionfunc greet(): print("Hello!")# Function with parametersfunc add(a: int, b: int) -> int: return a + b# Function with default parametersfunc spawn_enemy(type: String = "goblin", level: int = 1) -> void: print("Spawning ", type, " at level ", level)# Variadic functionfunc sum_all(values: Array) -> float: var total = 0.0 for value in values: total += value return total
Every Node has special methods that are called during its lifecycle:
node_lifecycle.gd
extends Node# Called when the node enters the scene tree for the first timefunc _ready() -> void: print("Node is ready")# Called every framefunc _process(delta: float) -> void: pass # Update logic here# Called every physics frame (60 FPS by default)func _physics_process(delta: float) -> void: pass # Physics calculations here# Called when input events occurfunc _input(event: InputEvent) -> void: if event is InputEventKey: print("Key pressed")
Every .gd file implicitly defines a class. Use extends to inherit from a base class:
extends Node2Dclass_name Player # Optional: gives the class a global namevar health: int = 100var speed: float = 200.0func take_damage(amount: int) -> void: health -= amount if health <= 0: die()func die() -> void: queue_free()
extends Node2D@export var speed: float = 100.0@export var max_health: int = 100@export var player_name: String = "Hero"# Export with ranges@export_range(0, 100) var volume: int = 50@export_range(0.0, 1.0, 0.1) var opacity: float = 1.0# Export node paths@export var target: Node2D@export var target_path: NodePath# Export files and directories@export_file var config_file: String@export_dir var data_directory: String# Export enums@export_enum("Warrior", "Mage", "Rogue") var character_class: String@export_flags("Fire", "Water", "Earth", "Air") var elements: int
# Type checkingvar x = 42print(typeof(x)) # Prints 2 (TYPE_INT)print(x is int) # Prints true# String conversionvar num = 42var text = str(num) # "42"var formatted = "Score: %d" % num# Range iterationfor i in range(5): print(i) # 0, 1, 2, 3, 4for i in range(2, 5): print(i) # 2, 3, 4# Lengthvar array = [1, 2, 3]print(len(array)) # 3var text = "Hello"print(len(text)) # 5# Load and preload resourcesvar scene = load("res://scenes/enemy.tscn")var texture = preload("res://images/player.png") # Loaded at parse time