Comparison Operators
Compare two values and return true or false. Used in Unity to compare player health, score, level, etc.
Size Comparison
-
>: true if left is greater- Example:
playerHp > 0→ true if health is greater than 0 (alive) - Example:
currentScore > highScore→ true if current score is higher than high score
- Example:
-
<: true if left is less- Example:
enemyHp < 10→ true if enemy health is less than 10 (weak state) - Example:
playerLevel < maxLevel→ true if player level is below max level
- Example:
Equality Comparison
-
==: true if two values are equal- Example:
playerHp == 0→ true if health is 0 (dead) - Example:
itemCount == maxInventorySize→ true if item count equals max inventory size
- Example:
-
!=: true if two values are different- Example:
playerHp != 0→ true if health is not 0 (alive) - Example:
currentWeapon != null→ true if current weapon exists
- Example:
Greater or Equal, Less or Equal
-
<=: true if left is less than or equal to right- Example:
playerHp <= 30→ true if health is 30 or below (danger state) - Example:
enemyCount <= 0→ true if there are no enemies or count is 0
- Example:
-
>=: true if left is greater than or equal to right- Example:
playerLevel >= 10→ true if level is 10 or above (can level up) - Example:
score >= targetScore→ true if score meets or exceeds target score
- Example:
Logical Operators
Used to combine multiple conditions. Essential for creating complex game logic in Unity.
OR Operator (||)
- Meaning: "or" - true if at least one is true
- Game example:
// If player is dead or game is over
if (playerHp <= 0 || isGameOver)
{
ShowGameOverScreen();
}
// Jump if spacebar or left mouse button is pressed
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
{
Jump();
}
Unity usage:
- Check if any of multiple input keys are pressed
- Execute if any of multiple conditions are met
- Player is dead or time ran out, etc.
AND Operator (&&)
- Meaning: "and" - true only if both are true
- Game example:
// Can use skill if health exists and mana is sufficient
if (playerHp > 0 && playerMana >= skillCost)
{
UseSkill();
}
// Give reward if level is 10+ and quest is completed
if (playerLevel >= 10 && questCompleted)
{
GiveReward();
}
Unity usage:
- Execute only when all conditions are met
- Check if item can be used (item exists, no cooldown, etc.)
- Check if boss can be defeated (weapon exists, health exists, etc.)
NOT Operator (!)
- Meaning: "not" - converts true to false, false to true
- Game example:
// Continue playing if game is not over
if (!isGameOver)
{
UpdateGame();
}
// Can attack if weapon is not null (weapon exists)
if (!(currentWeapon == null))
{
Attack();
}
// Or more simply
if (currentWeapon != null)
{
Attack();
}
Unity usage:
- Invert conditions
- Opposite of null check
- Execute when game state is not something