Menu
CoddyTech

Compare Numbers

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

Most conditions compare two values, and every comparison gives a bool:

  • a == b: a equals b. Two equals signs: one = puts a value in a variable.
  • a != b: a is not b
  • a < b and a > b: less than, greater than
  • a <= b and a >= b: less than or equal, greater than or equal

To ask two things at once, join them: && means and (both must be true), || means or (one is enough).

if (coins >= 10 && level == 3)
{
    Debug.Log("The shop is open");
}

Input.GetKeyDown(KeyCode.E) is a bool too, but unlike GetKey it is true only in the one frame the key goes down, so one press counts once however long the key is held.

challenge icon

Challenge

Easy

The door should open when the player has 3 keys or more and presses E.

  1. Below the K block in Update(), not inside it, write if (keys >= 3 && Input.GetKeyDown(KeyCode.E)).
  2. In its braces, write transform.position = new Vector3(0, 4.5f, 3);.

Press Play, press K three times, then E: the door slides up. Then Check.

Try it yourself

using UnityEngine;

public class KeyDoor : MonoBehaviour
{
    int keys = 0;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.K))
        {
            keys++;
            Debug.Log("Keys: " + keys);
        }

        // Open the door with 3 keys or more and a press of E:
        // move it to (0, 4.5f, 3).
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground