GDScript Fundamentals

Lesson 2 of 7

Variables and Types

GDScript is dynamically typed by default, like Python, but with optional static typing you can add for extra safety and editor autocompletion.

var xp = 0              # dynamically typed, inferred as int
var name := "Ada"        # := infers AND locks in the type (String)
var health: float = 100.0 # explicit static type annotation

xp += 10

var xp = 0 works exactly like Python, no type is enforced. var name := "Ada" (with a colon before =) tells the compiler to infer the type once and then enforce it, assigning a number to name later becomes a compile-time error instead of a silent bug.

Exported variables

A variable marked @export becomes editable directly in the Godot editor's Inspector panel, no code changes needed to tweak it:

extends CharacterBody2D

@export var speed: float = 300.0
@export var jump_velocity: float = -400.0

This is one of GDScript's most distinctive features, a game designer with no programming background can tune speed and jump_velocity by dragging a slider in the editor, without ever opening this file.

Common built-in types

var position := Vector2(100, 50)   # a 2D point/vector, everywhere in 2D games
var items := ["sword", "shield"]     # array
var stats := {"str": 10, "dex": 8}    # dictionary

Vector2 isn't just a convenience class, it has built-in math operators (+, -, *) that work exactly as you'd expect mathematically, since 2D position and movement math is something almost every game script needs constantly.

📝 Variables and Types Quiz

Passing score: 70%
  1. 1.What does marking a variable with @export do?

  2. 2.GDScript requires every variable to have an explicit static type declared.

  3. 3.The built-in type commonly used to represent a 2D point or movement vector is: ____