Unity Fundamentals — What if? What Else?!

Alain Schoovers
4 min readApr 2, 2021

--

What happens if the player is dead, what if your ammo has run out, what happens when we collect a powerup? All these scenarios can be set using “If statements”

If statements are used in a lot of programming languages and C# is no exception.

When programming there are a lot of cases where you want something to happen depending on what condition is met. It is a very powerful and straightforward tool in your programming arsenal but it can be confusing for someone new to programming.

So let's get to the bottom of these once and for all.

If

An if statement is nothing else than a container for some code that is only run if the condition is met (TRUE).

You first start the if statement by typing “if”, followed by “(CONDITION)” and after that “{}”, whatever code you will put inside these curly brackets is only run when the condition is met, if not it will skip this part and move on to the line after the last “}” in this case the code will only run when the _speed is greater than 5.

Else if

You can chain “if statements” with “else if statements” when you want to go through multiple scenarios which all have their own unique condition that has to be met.

In this case, the code will first look if the condition in the first if is met, if not it will check if the condition of the next else if is met and if not it will move to the next and so on.

Else

Else can be seen as the default state, if all the above conditions are not met the script will fall back on what is defined within the else statement.

The main difference between else and else if is that else does not need his own condition to be true as long as all the others are false it will automatically be triggered. Note that for this reason else does not have a condition within ().

If without else if or else

While you can chain logic you don't have to. you will often come across isolated if statements with no else clause. this is mainly used for simple behavior where you only want to trigger a piece of code when a certain condition is met but when it's not it does nothing, in this case only an if statement will do.

If this if is not met it will just continue along in the code looking for the next line to trigger.

For a lot of people familiar with Conditional logic and programming this might seem trivial but I still see a lot of confusion on this topic for people new to programming so thought it was worth clarifying.

I hope this gives you a clear understanding of what these statements are and how to use them.

Thanks for your time and I hope to see you in my next article!

--

--

No responses yet