An if statement checks if something is true or not before executing code. The syntax for an if statement can bee seen below.

if (condition) {

          Do something

}

A condition must be placed in the () after the if, where one thing relates to another thing or something is true/false. There are several different conditional syntax’s in C#. These are known as relational operators.

Condition Operator
Equal To ==
Greater Than >
Less Than <
Greater Than OR Equal To >=
Less Than OR Equal To <=
Something OR Something Else ||
Something AND something Else &&
Not Equal To !=

There are some others but if we end up using them I will point them out when we do.

There is also something called an else statement. These come after an if statement when there is another action that needs to take place if the if statement is not true. An else statement does not have a condition but must immediately follow an if statement to be used (an if statement does not require an else statement but an else statement requires an if statement).

else {

          Do Something Else

}

You can think of them as a switch > if A is true do B, else do C.

Before we do an example I should also mention Else If.

if…

else if (condition){

          Do Something

}

else…

We won’t be using this for a while (if at all) in this tutorial series but it is worth knowing about. These are used when there is more than one possible condition. If A is true do B, if C is true do D else do E.

Let’s use what we have just learnt and combine it with what we did in the last part (functions/methods). In MyScript, after TestMethod, add a new method called InitialisePlayer. Make it private and void without passing it anything.

Basics_IfElse001
InitialisePlayer

Now we can add an if statement to this method. We will check if playerName is null OR   “”.

Basics_IfElse003.JPG
If Statement

If playerName is either of these things we will set it equal to “Player”.

Basics_IfElse002.JPG
Do Something

Call this function in the Start method.

Basics_IfElse006.JPG
Calling InitialisePlayer

Make sure you save the script to apply any changes.

Now if the playerName is not set to anything it will automatically change to “Player”. You can try this out by deleting the name in the inspector, adding a debug.log to output the player name in InitialisePlayer (after playerName is set to player) and then hitting play.

Basics_IfElse005.JPG
No Name
Basics_IfElse007.JPG
Adding a Debug.Log
Basics_IfElse008.JPG
Console After Hitting Play

Now if you enter a name and hit play nothing should appear in the console. This is because the code contained in the if statement will only run when the name is null or “”.

Basics_IfElse009.JPG
Name
Basics_IfElse010.JPG
Empty Console

That concludes this part. In the next part we will look at the Input manager in Unity so we can set up some controls for our Ship.