GDScript Tutorial: Godot 4 Reference with Examples
A free GDScript reference for Godot 4: variables and static types, arrays and dictionaries, enums, match, functions and lambdas, classes, signals, await and Vector2. Every example runs on the page in real Godot, and the comparison pages set Godot beside Unity, Unreal, Python and C#.
Empezar el cursoPrimeros pasos
- What Is GDScriptGodot's main language is GDScript, a Python-like language built into the engine. Here is what it looks like, why Godot has its own language, and how C# and C++ fit in.
- Hello WorldWrite and run your first GDScript: extends, _ready(), print(), comments and indentation, and how Godot runs a script attached to a node.
Fundamentos
- VariablesHow to declare variables in GDScript with var, the difference between member and local variables, default values, and the scope rules that catch new Godot programmers.
- Static TypingHow optional static typing works in GDScript: typed variables, := inference, typed parameters and return types, casting with as, and why typed code is faster and safer.
- ConstantsHow const works in GDScript: naming, typed constants, constant arrays and dictionaries that are read-only, preload constants, and the built-in constants PI, TAU and INF.
- EnumsHow enums work in Godot 4: named and unnamed enums, custom values, printing an enum's name, looping over keys, typed enum variables, exporting enums and bit flags.
- Data TypesThe built-in data types of GDScript: int, float, bool, String, StringName, the vector and color types, Array, Dictionary, Object and null, plus how to check a type and convert between types.
- StringsWorking with text in GDScript: quotes and escapes, joining strings, length and indexing, searching, replacing, splitting and joining, trimming, case and comparing.
- String FormattingBuild text from values in GDScript with the % operator (%s, %d, %f, padding and decimals) and with String.format() placeholders, plus how to round a float for display.
- null and is_instance_validWhat null means in GDScript, how to check for it, why a freed node is not the same as null, and when to use is_instance_valid() instead of a null check.
Control de flujo
- if, elif, elseMake decisions in GDScript with if, elif and else, combine conditions with and, or and not, test membership with in, and write one-line choices with the ternary form.
- match StatementGDScript's match is its switch statement. Match values, several values at once, the _ wildcard, bound variables, array and dictionary patterns, and when guards.
- for LoopHow the for loop works in GDScript: looping a number of times, range() with a start, end and step, looping over arrays, dictionaries and strings, getting the index, and break and continue.
- while LoopHow the while loop works in GDScript, when to pick it over for, break and continue, the do-while pattern, and why an endless while loop freezes your Godot game.
Arrays y diccionarios
- ArraysEverything about arrays in Godot 4: create an array, add and remove items, check size and contents, sort, slice, copy, map, filter and reduce, and 2D arrays for grids.
- Typed ArraysTyped arrays in Godot 4 hold one type only. Declare Array[int] or Array[Node], pass them to functions, fix the "Trying to assign an array of type Array" error with assign(), and export them.
- Packed ArraysPacked arrays store one type tightly in memory: PackedInt32Array, PackedFloat32Array, PackedStringArray, PackedVector2Array and PackedByteArray. When to use them, how they differ from Array, and the overflow trap.
- DictionariesHow dictionaries work in Godot 4: create one, read with [] and get(), add and erase keys, check with has(), loop over keys and values, merge, copy, typed dictionaries and nested data.
Funciones
- FunctionsDefine and call functions in GDScript: parameters with types and default values, return values, returning several values, recursion, variadic functions and the virtual functions Godot calls for you.
- Lambdas and CallablesInline functions in Godot 4: write a lambda with func, store and call it, pass functions to map, filter and signals, add arguments with bind(), and understand how lambdas capture variables.
- Static FunctionsStatic functions and static variables in Godot 4: call a function without an instance, share one value across every instance, _static_init(), and when an autoload is the better choice.
Clases y objetos
- ClassesIn GDScript every script is a class. Name it with class_name, create instances with new(), write a constructor with _init(), add methods, print an object with _to_string(), and free what you create.
- InheritanceHow inheritance works in GDScript: extend a class, override methods, call the parent with super, pass arguments to the parent constructor, and treat child classes as their parent type.
- Inner ClassesDefine small helper classes inside a GDScript file with the class keyword: instances, constructors, extending, reaching an inner class from another script, and what an inner class can and cannot see.
- Setters and GettersRun code whenever a property is read or written. The Godot 4 set and get syntax, clamping values, computed properties, emitting a signal on change, and the setget changes from Godot 3.
- ResourcesWhat a Resource is in Godot 4, how to write a custom resource class for item or enemy data, edit it in the Inspector, save and load it as a .tres file, and why shared resources surprise people.
Lo esencial de Godot
- Scene TreeHow nodes and the scene tree work in Godot 4 from GDScript: parents and children, finding nodes with get_node() and $, adding and removing nodes in code, groups, and the order Godot calls _ready().
- SignalsSignals let a node announce that something happened without knowing who listens. Declare a signal, connect it to a function or a lambda, emit it with arguments, disconnect it, and use the engine's built-in signals.
- await and Coroutinesawait pauses a function until a signal fires or another coroutine finishes, without freezing the game. Wait for a timer, an animation or a player's choice, return values from coroutines, and avoid the common traps.
- Vector2Vector2 is how Godot stores 2D positions, directions and velocities. Create vectors, add and scale them, get length and distance, normalize a direction, use angles, and move toward a target.
- @export Variables@export shows a variable in Godot's Inspector so you can tune it without editing code. Export numbers with ranges, enums, files, nodes, resources and arrays, group them, and avoid the default value trap.
- @onready@onready delays a variable's value until the node is in the scene tree, which is when $Child paths work. See when it runs, the null instance error it prevents, and how it compares with @export.
- Random NumbersRandom numbers in Godot 4: random integers and floats in a range, picking a random array item, shuffling, weighted loot drops, seeds for repeatable results and RandomNumberGenerator.
- Math FunctionsThe math helpers a Godot game uses every day: clamp a value, lerp toward a target, wrap around a range, move_toward, snapped, rounding, min and max, angles in radians, and frame-rate independent smoothing.
Depuración
- print and DebuggingFind bugs in a Godot game: print values well, print_rich, push_warning and push_error, assert, print_stack, breakpoints and the debugger, and the remote scene tree.
- Error MessagesThe GDScript errors beginners meet most, with the exact Godot 4 message, what it means and the fix: null instance, Nil, not declared in the current scope, invalid index, indentation, invalid operands and node not found.
Comparativas
- Godot vs UnityA fair comparison of Godot 4 and Unity 6: license and cost, languages, 2D and 3D, platforms, learning curve, jobs and community, with the same script written in both, and a clear way to choose.
- Godot vs UnrealGodot 4 and Unreal Engine 5 compared on cost, languages, 2D and 3D, hardware, team size and jobs, plus a three-way table with Unity and advice on which engine fits your game.
- GDScript vs PythonGDScript looks like Python but is a different language. Side-by-side examples of what is the same, what differs (var, func, typing, division, no comprehensions, no libraries) and how a Python programmer gets productive in Godot fast.
- GDScript vs C#Godot supports GDScript and C#. Compare syntax side by side, setup, speed, editor integration, platform support and career value, and see when to pick each, or mix both in one project.