C# Basics: If/Then Statements

Sabrina Windsor
2 min readMay 15, 2021

--

Now that we know what variables are and how to assign them, how do we get stuff to actually do something? Well we can use if statements. They basically follow this format:

Basically if a certain condition were to pass in the game (this is what would be stated in the parentheses), then, and only then, would the code that is in the following brackets get called up to play. If the condition doesn’t happen, the code won’t do anything.

For instance, let’s say we have a generic point system. It starts at zero, and whenever we press “space”, ten points get added. We’ll have to declare an int variable, I’ll name it “_points”, and the code should look like this:

I did make _points public, so I can see the change in the inspector

Now, whenever we hit the space button, the points number should increase by ten. Now what if we want to decrease points? Do we have to make a whole separate if statement?

Nope!

At least, for organizational purposes, we can just add on another condition using else if. So let’s say if we press backspace, 5 points are subtracted. The whole thing will look like this:

Now what happens if we accidently press a different button?

Well, nothing would happen since we didn’t code anything to happen with that scenario. If we want something else to happen, then we can finish of the statement with else.

So if neither of the two prior conditions are met, our code will default to this. The code will look like this:

We don’t need a condition for else, as we don’t have any specific button we want to act as a trigger. So if you were to press “enter” instead of space or backspace, the console will tell you that you pressed the wrong button. The same thing would happen if you pressed “delete”, or “a”, etc.

Now you know the basics of how if statements work! We’ll be using them a lot down the road in our Unity Development journey, so be sure to do lots of practice! Happy coding!

--

--

Sabrina Windsor
Sabrina Windsor

Written by Sabrina Windsor

Currently learning to code with the help of GamedevHQ in order to someday my my game ideas come to life!

No responses yet