while repeats a block as long as a condition is true. Godot checks the condition before every pass:
Turn 1: hp 6
Turn 2: hp 2
Turn 3: hp -2
Defeated after 3 turns
If the condition is false from the start, the body never runs.
while or for?
- Use for when you know what to loop over:
for i in 10,for enemy in enemies. - Use
whilewhen you loop until something happens and do not know how many passes that takes.
Doubling a value until it passes a limit is a while job:
10 upgrades, next costs 1024
break and continue
break leaves the loop at once. continue jumps back to the condition check:
1
3
5
7
A do-while Loop
GDScript has no do ... while. Write while true: and put the check at the end, so the body runs at least once:
Rolled a 6 after 5 tries
seed(3) makes the random numbers repeat on every run, so the result is the same each time you press Run. See random numbers.
Endless Loops Freeze the Game
A loop runs inside a single frame. While it runs, Godot cannot draw, play sound or read input, so a while that never ends freezes the whole game. This code waits for a key the wrong way:
func _ready():
while not Input.is_action_pressed("jump"):
pass # the game freezes here: the input never updates
print("Jump!")
Input only updates between frames, so the condition never changes. Check once per frame instead, or wait on a signal with await:
func _process(delta):
if Input.is_action_just_pressed("jump"):
print("Jump!")
A good rule: in game code, a while loop should always finish within the same frame. Anything that should happen over time belongs in _process(), a Timer or a coroutine.
Frequently Asked Questions
How do I write a while loop in GDScript?
Write while condition: and indent the body. Godot checks the condition before each pass and stops when it is false: while hp > 0: keeps looping until hp reaches 0 or less.
Does GDScript have a do while loop?
No. Write while true: with the body first and if not condition: break at the end. The body then always runs at least once.
Why does my Godot game freeze in a while loop?
A loop runs inside one frame, and the game cannot draw or read input until it ends. A while whose condition never becomes false never ends. To wait for something in a game, check it once per frame in _process() or use await on a signal.
When should I use while instead of for?
Use for when you know what to loop over: a count, a range or an array. Use while when you loop until something happens and you cannot know in advance how many passes it takes.