Conditions and ‘if’ statements

This afternoon I learned about conditions and ‘if’ statements. Conditional statements in code let you specify circumstances for things. If a statement is true, a block of code will run. There are three main parts to a conditional statement:

  • The keyword ‘if’
  • The condition – The question that is in between the brackets
  • A body – The code that will only run if the condition is true

 

To apply ‘if’ statements, we then made a heads or tails code. The only random numbers that can be generated with ‘Random.Range’ are including the first number, but can only be smaller than the second number, so with the code below, the number could only be 1, or 2. The piece of code under that only runs if the number generated is 1.

void Start() {
int number = Random.Range (1, 3);

if (number == 1) {
Debug.Log (“Heads”);
}
}

We then learned about operators. Operators are the symbols that define what a condition is. Here are the important examples.

  • == – asks if variable is equal to entered number
  • = – tells the variable it equals the entered number
  • ! – variable is not equal to entered number
  • > – variable is larger than entered number
  • < – variable is smaller than entered number

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s