Selection statements
The most complex programming problems can often be boiled down to sets of simple choices that a game or program evaluates and acts on. Since Visual Studio and Unity can't make those choices by themselves, writing out those decisions is up to you.
The if-else
and switch
selection statements allow you to specify branching paths, based on one or more conditions, and the actions you want to be taken in each case. Traditionally, these conditions include the following:
- Detecting user input.
- Evaluating expressions and Boolean logic.
- Comparing variables or literal values.
You're going to start with the simplest of these conditional statements, if-else
, in the following section.
The if-else statement
if-else
statements are the most common way of making decisions in code. When stripped of all its syntax, the basic idea is: If my condition is met, execute this block of code; if it's not, execute this other block of code. Think of these statements as gates,...