If Statements

The variables change potentially in many different circumstances. Like when the level changes, when the player changes their position, and so on. Accordingly, you will often need to check the value of a variable to branch the execution of your scripts that perform different sets of actions depending on the value.

For example, if bikesPetrol reaches 0 percent, you will perform a death sequence, but if bikesPetrol is at 20 percent, you might only display a warning message.

C# offers two main conditional statements to achieve a program branching like this in Unity. These are the switch statement and if statement.

The ?if statement? has various forms. The most basic form checks for a condition and will execute a subsequent block of code if and only if the condition is true.

Let?s see one simple example:

Attach this script file to the GameObject?s component. And when you play this project, it will display the following output in console:

If Statements

If else Statement

Let's see one example for if-else statement:

Output:

If Statements
Next TopicLoops




Contact US

Email:[email protected]

If Statements
10/30