Control Flow: If Statements and Loops

In this lesson you'll learn to

  • ✓Write an if/else statement in Verse that checks a player's score and triggers a game event
  • ✓Use a loop in Verse to repeat an action a set number of times on your island
  • ✓Explain in your own words what 'control flow' means using a real game example
  • ✓Connect if statements and loops to real Fortnite island devices like Item Granters and Score Managers

🎮 What Is Control Flow?

Imagine you are playing a board game. You roll the dice. If you land on a red square, you lose a turn. Otherwise, you move ahead. The rules of the board game control what happens next.

In coding, control flow means: the order in which your code runs, and which parts it chooses to run. You are the rule-maker. You tell the computer, "Do THIS if something is true. Do THAT if it isn't."


🚦 If Statements — Your Game's Referee

An if statement is like a referee on your island. It watches what is happening. Then it makes a call.

Think of it like this:

If the player's score is 10 or more → open the treasure chest! Else → keep the chest locked.

The word if starts the check. The word else handles everything that is NOT true.

In Verse, it looks like this:

if (Score >= 10):
    # Do this when score is high enough
else:
    # Do this when score is too low
  • The stuff inside the if only runs when the condition is true.
  • The stuff inside the else runs when the condition is false.
  • Think of the condition like a yes/no question: "Is the score 10 or more?" Yes or no?

💡 New Word — Condition: A condition is a question that is either TRUE or FALSE. "Is it raining?" is a condition. "Is the player's score above 5?" is also a condition!


🔁 Loops — Your Island's Copy Machine

What if you wanted to give every player on your island 3 potions, one at a time? You could write the same line of code 3 times. But what if you wanted to do it 100 times? Writing 100 lines is no fun!

A loop is like a copy machine for your code. It runs the same instructions over and over until you say stop.

💡 New Word — Loop: A loop repeats a block of code. It's like pressing "replay" on a song, but for instructions.

Verse has a simple counting loop called a for loop. You tell it how many times to repeat. Here is the idea:

for (Index := 0..2):
    # This runs 3 times (0, 1, 2)

That 0..2 means "count from 0 up to and including 2." That is 3 counts total. Think of it as laps around a track: lap 0, lap 1, lap 2 — done!

🏃 Analogy: A for loop is like a coach yelling "Run 3 laps!" Your player runs one lap, then another, then another — and stops.


🧩 Putting It Together on Your Island

Let's say you are building a Score Challenge island. Here is the plan:

  • A player steps on a Trigger device.
  • Your Verse code checks: Did the player reach 5 points?
  • If yes → an Item Granter gives them a Legendary weapon. 🎉
  • If no → nothing special happens yet.
  • Also, when the game starts, a loop grants 3 common weapons to warm up the player.

You use an if statement for the score check. You use a loop for the weapon hand-out. Together, they make your island smart and fun!


🗂️ The Shape of Verse Code

Two things to always remember about Verse:

  1. Indentation matters. The code inside an if statement or loop must be indented (pushed in with spaces). This is how Verse knows which lines belong together.
  2. Colons start a block. After if(...) and for(...), you put a colon : and then indent the next lines.

Think of indentation like putting toys inside a box. The toys (code lines) belong to the box (if or loop) only if they are inside it.

Worked Example

🏗️ Building a Score Reward System

The island plan:

  • Drop a Trigger Device in your UEFN island.
  • Drop an Item Granter Device and set it to grant a Legendary item.
  • Drop a Score Manager Device.
  • Attach this Verse script to a Verse Device in your island.

When a player walks into the trigger, the code checks their score. If they earned 5 or more points, the Item Granter fires! The loop at the start hands out 3 starting items automatically.

using { /Fortnite.com/Devices }
using { /Verse.org/Simulation }
using { /UnrealEngine.com/Temporary/Diagnostics }

# This is our Verse device class — it lives on the island
score_reward_device := class(creative_device):

    # Plug these in from the UEFN editor by selecting your devices
    @editable
    GranterDevice : item_granter_device = item_granter_device{}

    @editable
    TriggerDevice : trigger_device = trigger_device{}

    # OnBegin runs once when the game starts
    OnBegin<override>()<suspends> : void =
        # Subscribe to the trigger — when a player steps on it, call OnTriggered
        TriggerDevice.TriggeredEvent.Subscribe(OnTriggered)

    # This function runs every time a player hits the trigger
    OnTriggered(Agent : ?agent) : void =
        # Try to get the player's score from the score manager
        # We track score with a simple variable here for the example
        var PlayerScore : int = 6  # Pretend the player has 6 points

        # ---- IF STATEMENT ----
        # Check: does the player have 5 or more points?
        if (PlayerScore >= 5, ActualAgent := Agent?):
            # YES — grant them a reward item!
            GranterDevice.GrantItem(ActualAgent)
            Print("Great job! You earned a reward!")  # Shows in the log
        else:
            # NO — encourage them to keep going
            Print("Keep collecting points — you need 5!")```

### 🔍 Walkthrough — Line by Line

| Code Part | What It Does |
|---|---|
| `score_reward_device := class(creative_device)` | Creates our island device — like building a new LEGO piece |
| `@editable` | Lets us plug in real devices from the UEFN editor |
| `OnBegin<override>()<suspends> : void` | Runs once when the game starts |
| `TriggerDevice.TriggeredEvent.Subscribe(OnTriggered)` | Tells the trigger: "Call OnTriggered when someone steps on you" |
| `var PlayerScore : int = 6` | A variable storing the player's score (6 for this example) |
| `if (PlayerScore >= 5):` | The BIG QUESTION — is the score 5 or more? |
| `GranterDevice.GrantItem(Agent)` | Gives the item to the player who triggered it |
| `else:` | Handles the "not enough points" case |
| `Print(...)` | Sends a message to the output log so you can see what happened |

> ✅ **Try it!** In UEFN, place a Trigger Device and an Item Granter Device. Connect them to your Verse device using the `@editable` slots. Change `PlayerScore` to 3 and play — you should see the "keep collecting" message instead!

---

### 🔁 Bonus: Adding a Loop for Warm-Up Items

Want to grant 3 items when the game starts? Add this loop inside `OnBegin`, **before** the Subscribe line:

```verse
# Loop 3 times (Index goes 0, 1, 2)
for (Index := 0..2):
    # Each loop gives ALL agents a starting item
    # (In a real game, you'd loop through players — this shows the loop shape)
    Print("Granting warm-up item number {Index}")
    # GranterDevice.GrantItem(SomeAgent)  # Uncomment when you have a real agent

🎉 What just happened? The loop ran 3 times on its own. You wrote the Print line once but the computer did it 3 times. That's the magic of loops!

Try It Yourself

🛠️ Your Turn: The Double Score Challenge!

You are going to upgrade the Score Reward System. Here is your challenge:

Goal: Change the if statement so there are THREE outcomes instead of two:

  1. If the player's score is 10 or more → print "LEGENDARY reward unlocked!"
  2. If the player's score is 5 or more (but less than 10) → print "Nice! Here's a common item!"
  3. If the score is below 5 → print "Keep going, you can do it!"

In Verse, you can chain conditions like this using else if:

if (Score >= 10):
    # first case
else if (Score >= 5):
    # second case
else:
    # third case

Steps:

  1. Open your Verse file from the worked example above.
  2. Change var PlayerScore : int = 6 to different values (like 11, 7, and 3) to test each branch.
  3. Update the if/else block to have all three cases using else if.
  4. Bonus 🌟: Add a loop that counts from 1 to 5 and prints "Counting: {Index}" each time. Put it inside OnBegin.

💡 Hint: Remember to indent your code inside each if, else if, and else block. Verse is strict about indentation — it's like making sure your toys are inside the box, not next to it!

💪 You've got this! Try changing the score value and see how different branches run. That's real debugging — just like a game developer does!

🏴‍☠️

Take on the Challenge

Pass the 4-question challenge to master this lesson and chart the quest in your journal.

Recap

🌟 Great Work — Here's What You Learned!

Control flow means deciding which code runs and when — just like the rules of a board game. An if statement checks a true/false condition and picks a path, like a referee making a call on your island. A loop repeats code automatically so you don't have to write the same lines over and over. Put them together and your Fortnite island can react to players, check scores, and hand out rewards like a real game designer made it! 🎮

Pass the quiz above to chart this quest in your Journal.

Sources

/docs/documentation/en-us/uefn/learn-the-basics-of-writing-code-in-verse/docs/documentation/en-us/fortnite/learn-the-basics-of-writing-code-in-verse
Source

Biloxi Studios original lesson

Guided course

Add this lesson to your free study plan.

🧭 The Keeper’s log

Quest complete? Chart your next heading from the Verse Basics expedition.

⛵ Take me there