101 with If Condition.
Objective: 101 with If Condition.
If condition choose the code to execute when the condition is true.
Syntax for If Condition
1 if key word
2 double parentheses, inside this go the condition
3 open and close curly bracket
To understand this lets create a variable ,for a int called health ,then give it value of 3
If we pass health and check if health is greater or equal to one then print we alive. To print we use built-in method called Debug.Log(“”),then we write whatever we like in the double quote for now write we are alive.
This won’t Work
Because if statement run inside a method only and not outside a method.
Solution
For Testing purpose lets use built-in method called Start ,this method called when we play the editor. I will show you how to write this I won’t explain this we will talk about method in the later article.
Then Lets take our if condition inside the Start method.
Note: Type the if statement inside the Start method don't copy ,especially if you are beginner, cos if you copy you prepare to fail as software engineer.
Attach this script to main camera ,go to unity editor right click and hold then move your mouse to drag the script to the main camera. You can attacth this script direct to the hierarchy on the main camera by drag and drop it or select main camera then drag and drop the script to the inspector< Main camera.
But what happened if condition is false.
The code inside the if condition won’t run.
Else statement.
else statement will run when if condition is false .its written using else key word with double curly bracket.
Else if Statement.
Its written use keyword else if ,with double parentheses and double curly bracket .We use this to check same condition multiple times, we can add else as the last statement.
See you in the next article.