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 ba < banda > b: less than, greater thana <= banda >= 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
EasyThe door should open when the player has 3 keys or more and presses E.
- Below the K block in
Update(), not inside it, writeif (keys >= 3 && Input.GetKeyDown(KeyCode.E)). - 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground