C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
If StatementsThe 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: using System.Collections; using System.Collections.Generic; using UnityEngine; public class IfStatement : MonoBehaviour { public int myNumber = 10; // Use this for initialization void Start() { if (myNumber > 5) { print("myNumber is greater than 5"); } } // Update is called once per frame void Update() { } } Attach this script file to the GameObject?s component. And when you play this project, it will display the following output in console: If else StatementLet's see one example for if-else statement: using System.Collections; using System.Collections.Generic; using UnityEngine; public class IfStatement : MonoBehaviour { public int myNumber = 15; // Use this for initialization void Start() { if (myNumber == 10) { print("myNumber is equal to 10"); } else if (myNumber == 15) { print("myNumber is equal to 15"); } else { print("myNumber is not equal to 10"); } } // Update is called once per frame void Update() { } } Output:
Next TopicLoops
|