Menu
CoddyTech

If and Else

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 6 of 85.

A bool holds one of two values: true or false. Is the door open? Is the player on the ground? Is the game over?

bool gameOver = false;

An if runs its lines only when its condition is true, and an else runs its lines when it is not. The braces { } hold the lines that belong to each part:

if (gameOver)
{
    transform.position = new Vector3(0, -2, 0);
}
else
{
    transform.position = new Vector3(0, 2, 0);
}

This sinks an object out of sight when the game is over and keeps it up while the game goes on. Code like this goes inside a method, such as Update(), never after the class's last }.

Unity answers questions with bools too. Input.GetKey(KeyCode.Space) is true while the player holds the space bar and false the rest of the time, so Update() can ask it every frame.

challenge icon

Challenge

Easy

Holding Space should lift the gate.

  1. Below the two comments in Update(), write if (open) with transform.position = new Vector3(0, 3, 0); in its braces.
  2. After it, write else with transform.position = new Vector3(0, 1, 0); in its braces.

Press Play, click the game and hold Space: the gate rises, and drops when you let go. Then Check.

Try it yourself

using UnityEngine;

public class Gate : MonoBehaviour
{
    void Update()
    {
        bool open = Input.GetKey(KeyCode.Space);

        // If open is true, move the gate to (0, 3, 0).
        // Otherwise, move it to (0, 1, 0).
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground