Switch in GDScript
Our first program will demonstrate the usage of switch
statements, which express conditionals across many branches.
Basic switch
Statement
Here’s a basic switch
example in GDScript:
Multiple Expressions in case
and default
case
You can use commas to separate multiple expressions in the same case
statement. We use the optional default
case in this example as well.
switch
Without an Expression
match
without an expression is an alternate way to express if/else logic. Here we also show how the case
expressions can be non-constants.
Type switch
A type match
compares types instead of values. You can use this to discover the type of a value. In this example, the variable t
will have the type corresponding to its clause.
Running the Code
To run the program, put the code in a GDScript file, attach it to a Node, and run the scene.
Outputs:
In this example, we’ve learned how to use switch
(or match
in GDScript) to handle multiple conditional branches efficiently.