Want your game to say “You Win!” when score hits 100?
Or make the player jump only when they’re on the ground?
Time to learn conditional logic — the magical power of if and else.
🤔 What is a Conditional Statement?
A conditional lets your code ask a question, and do something based on the answer.
Example:
if (score >= 100)
{
Debug.Log("You win!");
}
This checks if score
is greater than or equal to 100.
If it is — boom, message appears. If not — nothing happens (yet).
🧰 Common Comparison Operators
Symbol | Meaning | Example |
---|---|---|
== | Equal to | if (lives == 0) |
!= | Not equal to | if (lives != 3) |
> | Greater than | if (score > 50) |
< | Less than | if (speed < 10) |
>= | Greater or equal to | if (score >= 100) |
<= | Less or equal to | if (health <= 0) |
🔀 Using else
and else if
Basic else
:
if (health <= 0)
{
Debug.Log("Game Over!");
}
else
{
Debug.Log("Keep fighting!");
}
Chaining with else if
:
if (score >= 100)
{
Debug.Log("Gold Medal!");
}
else if (score >= 50)
{
Debug.Log("Silver Medal!");
}
else
{
Debug.Log("Try Again!");
}
This allows multiple conditions — great for scoring, levels, and enemy behavior.
🧪 Unity Example: Player Health
using UnityEngine;
public class HealthCheck : MonoBehaviour
{
public int health = 100;
void Start()
{
if (health <= 0)
{
Debug.Log("Game Over!");
}
else
{
Debug.Log("You’re still alive. Barely.");
}
}
}
Try changing the health
value in the Inspector and see what message you get when you hit Play.
🔄 Combine with Variables and Methods
Conditional logic becomes powerful when mixed with other tools:
void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
Suddenly your game has life and death stakes!
🧠 Recap
if
checks a condition and runs code only if it’s true- Use
else
to do something if the condition is false else if
adds more options to your logic tree- Great for score checks, game over logic, power-ups, and more
🧪 Mini Challenge: Damage Logic
- Create a script called
EnemyHealth.cs
- Add a
public int health = 50;
- Add a method
TakeHit(int damage)
- Inside, check if health is 0 or below
- If yes → print “Enemy defeated!”
- If no → print “Enemy still standing”
Then call it with a few values and test different outcomes.
🚀 What’s Next?
Let’s crank up the logic with loops – the ultimate tool for repeating actions like spawning enemies, counting down, or charging attacks.
🔁 Go to Lesson 10 → Loops (for
, while
) in Unity C#