C# Basics - if-else Statements
What will happen if the condition is met?
Ever thought about why a menu only opens up if you press the, let’s say, ESC key on your keyboard? Or the menu button on your controller?
Why does the player only attack when you press X on your controller and only jumps when you press the A button on it?
All of these things are conditions. If the player presses the A button, then DoJump().
Noticed the method I used here? That’s what’s going on inside script. It checks for input on the key you want and if it is detected, it will then do some logic.
Let’s break that down into a simple example.
Let’s say we want to create a very simple program which only prints out that we have money as long as the money counter is higher than zero.
Letting Rider auto-complete the if statement, we get the following lines of code:
So what we need to do is to input a condition and what should happen if the condition is met.
The condition for us would be that the current money is higher than nothing. So we just need to create a variable which stores the value and create the condition.
As we want to print out some text, we just want to use Debug.Log() for the logic part.
What if the condition is not met?
Let’s say we have available money at 0. What will happen with the code we already have? You guessed it, nothing.
If we want something to happen, we simply need to use the else statement.
Let’s say we want to print out another text, stating that we are out of money:
And that’s all we need to do!
A quick tip for you at the end
You might have noticed, that I left out the curly braces in the code snippets. Since C#7, you’re allowed to do that as long as the logic contains just a single line of code. If you try that with two lines, you’ll get an compiler error.
Thank you for your time!