🧠 If This, Then That – Writing Decisions in Code

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:

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

SymbolMeaningExample
==Equal toif (lives == 0)
!=Not equal toif (lives != 3)
>Greater thanif (score > 50)
<Less thanif (speed < 10)
>=Greater or equal toif (score >= 100)
<=Less or equal toif (health <= 0)

🔀 Using else and else if

Basic else:

Chaining with else if:

This allows multiple conditions — great for scoring, levels, and enemy behavior.


🧪 Unity Example: Player Health

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:

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

  1. Create a script called EnemyHealth.cs
  2. Add a public int health = 50;
  3. Add a method TakeHit(int damage)
  4. 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#