Title here
Summary here
Branching with if
and else
in GDScript is straightforward.
func _ready():
# Here's a basic example.
if 7 % 2 == 0:
print("7 is even")
else:
print("7 is odd")
# You can have an `if` statement without an else.
if 8 % 4 == 0:
print("8 is divisible by 4")
# Logical operators like `and` and `or` are often
# useful in conditions.
if 8 % 2 == 0 or 7 % 2 == 0:
print("either 8 or 7 are even")
# A variable can be declared and initialized before the condition;
# this variable will be available in the current and all subsequent branches.
var num = 9
if num < 0:
print(str(num) + " is negative")
elif num < 10:
print(str(num) + " has 1 digit")
else:
print(str(num) + " has multiple digits")
Note that you don’t need parentheses around conditions in GDScript, but the colon :
at the end of the condition and proper indentation are required.
To run this script in Godot:
_ready()
function.The output will be:
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
In GDScript, there is no ternary operator like in some other languages. You’ll need to use a full if
statement even for basic conditions.