The "Game Start" Button: Mastering OnBegin in Verse
Unverified — this example may not compile as-is.
The Verse code below did not pass our automated compile check, so it isn't marked verified and is hidden from the guide listing. The explanation may still be useful, but treat the code as a draft and adapt it before use.
The "Game Start" Button: Mastering OnBegin in Verse
You've built the map. You've placed the traps. You've even coded the logic that makes the floor disappear when you step on it. But there's one problem: nothing happens until a player actually interacts with it. It's like having a fully loaded shotgun in your inventory, but the gun only fires if you manually pull the trigger every single time.
What if you want your trap to arm itself the second the match starts? What if you want your boss to spawn exactly when the storm closes in, without waiting for a player to walk into a trigger zone?
Enter OnBegin.
In Verse, OnBegin is your "Game Start" button. It's the specific moment when your island transitions from "Editor Mode" (where you're just arranging furniture) to "Running Mode" (where the chaos begins). This tutorial will teach you how to use OnBegin to create a "Revenge Trap" that automatically targets the last player who eliminated you, setting the stage for your comeback before the first bullet is even fired.
What You'll Learn
- The Scene Graph Basics: Understanding that everything in your map is an "Entity" (a game object) with specific "Components" (attributes).
- The
OnBeginEvent: How to hook into the exact moment the game starts. - Variables: Storing data (like a player's ID) so your trap remembers who to target.
- Real-Time Logic: Making things happen automatically without player input.
How It Works
1. The Scene Graph: Your Map is a Family Tree
Before we code, we need to understand how Verse sees your map. In Unreal Engine (the engine behind Fortnite), your map isn't just a flat image. It's a Scene Graph.
Think of the Scene Graph like your Battle Bus roster.
- Entity: An Entity is any object in the game—a player, a wall, a prop-mover, or a Verse Script. It's like a specific player in the lobby.
- Component: Components are the traits or items that Entity carries. A player has a "Health" component and a "Weapon" component. A wall has a "Physics" component.
- Script: A Verse Script is a special kind of Entity that holds logic. It's like a custom rulebook attached to a specific object.
When you write Verse, you are usually attaching your script to a specific Entity (like a Trigger Volume or a Prop Mover).
2. The Two Phases of Life: Editor vs. Game
Every Entity in Fortnite has two states:
- Editor Mode: You are in UEFN (Unreal Editor for Fortnite). You can move things around, change colors, and break things without consequences. This is like the creative lobby before the match starts.
- Running Mode: The match has started. Players are alive, the storm is closing, and code is executing.
Most code in Verse only runs during Running Mode. If you try to run complex logic while in Editor Mode, it won't work because the game world isn't "active" yet.
3. OnBegin: The Kickoff Whistle
This is the core concept. OnBegin is a special function (a block of code that performs a task) that the game engine calls automatically the moment the map switches from Editor Mode to Running Mode.
- Analogy: Imagine a bomb squad defusing a device.
- Editor Mode: The bomb is on the table. The technician is inspecting it, but it's not armed.
OnBegin: The technician steps back, and the countdown starts. This is the exact millisecond the device becomes "live."- Running Mode: The clock is ticking. If someone touches it, it explodes.
If you want your trap to know who eliminated you before the match starts (so it's ready to go), you have to set up that memory during OnBegin.
4. Variables: The "Last Seen" Logbook
To make our Revenge Trap work, we need to remember who killed us. In programming, we use a Variable.
- Variable: A named container that holds a value that can change. Think of it like a scoreboard or a logbook.
- Constant: A value that never changes, like the speed of the storm or the max health of a player.
We'll use a variable to store the Player (a reference to a specific player agent) of the person who eliminated us.
Let's Build It
We are going to build a Revenge Prop-Mover. When you die, the system remembers your killer. When the match starts (OnBegin), our trap activates and targets that specific player.
Step 1: Setup in UEFN
- Create a new Verse Script. Name it
RevengeTrap. - Place a Prop-Mover in your map. Let's call it "The Anvil."
- Place a Trigger Volume slightly above the Anvil. This is where the victim will stand.
- Place a Player Spawn Point nearby.
- Add a Script component to the Trigger Volume and link it to your
RevengeTrapscript.
Step 2: The Verse Code
Here is the complete code. Don't worry if it looks scary—we'll break it down line by line.
# RevengeTrap.verse
# This script makes a trap remember who killed you and target them on start.
using { /Fortnite.com/Devices }
using { /Fortnite.com/Game }
using { /Verse.org/Simulation }
using { /UnrealEngine.com/Temporary/Diagnostics }
revenge_trap := class(creative_device):
# 1. Define the devices we need to interact with.
# These are set via the Details panel in UEFN by dragging the devices in.
@editable
Trigger : trigger_device = trigger_device{}
# The Prop Mover is the weapon we want to drop.
# Wire this up in the UEFN Details panel by selecting your "Anvil" prop mover.
@editable
Anvil : prop_mover_device = prop_mover_device{}
# 2. Create a Variable to store the killer's agent reference.
# This is like a logbook entry. It starts empty (?agent holds an optional value).
var KillerAgent : ?agent = false
# 3. The "OnBegin" Event.
# This function runs exactly once when the match starts.
OnBegin<override>()<suspends> : void =
# Get all players currently in the game via the fort_playspace.
# GetPlayspace() returns the active playspace for this island.
Playspace := GetPlayspace()
AllPlayers := Playspace.GetPlayers()
# Check if there are any players.
if (AllPlayers.Length > 0):
# Store the first player's agent reference in our variable.
# AllPlayers[0] returns an ?agent (optional), so we unwrap it with 'if'.
if (FirstPlayer := AllPlayers[0]):
set KillerAgent = option{FirstPlayer}
# Print a message to the debug log (Output Log in UEFN).
# This confirms OnBegin ran successfully.
Print("Match Started! Targeting a player.")
# Arm the trap: tell the Anvil prop mover to activate.
# Enable() makes the prop mover start its movement sequence.
Anvil.Enable()
Print("Anvil Armed! Waiting for target...")
else:
Print("No players found. Trap remains dormant.")
# 4. A Helper Function to check if a specific agent matches our stored killer.
IsTargetInZone(InAgent : agent) : logic =
# Unwrap our optional KillerAgent and compare it to the incoming agent.
if (Killer := KillerAgent?):
return Killer == InAgent
return false```
### Code Walkthrough
1. **`revenge_trap := class(creative_device)`**:
* This defines our **Script**. In Verse, every island script inherits from `creative_device`, which is the real base class for all UEFN devices.
* The `:=` syntax declares a new named class.
2. **`@editable` / `Trigger : trigger_device` and `Anvil : prop_mover_device`**:
* These are **editable fields**. The `@editable` attribute exposes them in UEFN's Details panel so you can drag your placed devices directly into these slots—no string-based scene searching needed.
* `trigger_device` and `prop_mover_device` are real Verse device types from `/Fortnite.com/Devices`.
3. **`var KillerAgent : ?agent = false`**:
* This is our **Variable** for storing a reference to the killer.
* `?agent` is an *option type*—it either holds an `agent` or is empty (`false` in Verse means "no value" for option types).
* `var` marks it as mutable so we can update it later.
4. **`OnBegin<override>()<suspends> : void`**:
* This is the **Event Handler**.
* `<override>` tells Verse, "I am replacing the default `OnBegin` behavior with my own."
* `<suspends>` allows the function to use asynchronous operations like `Sleep()` or `Await`.
* `: void` means this function doesn't return any data; it just *does* something.
* Everything indented beneath it runs when the game starts.
5. **`GetPlayspace()` and `.GetPlayers()`**:
* `GetPlayspace()` retrieves the active `fort_playspace` for the island—the real API for accessing game-session data in UEFN.
* `.GetPlayers()` returns a `[]player` array of all agents currently in the session.
* # note: `GetPlayspace()` is available on `creative_device` via `/Fortnite.com/Game`.
6. **`Anvil.Enable()`**:
* Calls the real `prop_mover_device` method that starts the device's movement sequence—equivalent to pressing "Enable" on the device in-game.
7. **`Print(...)`**:
* The real Verse logging function from `/UnrealEngine.com/Temporary/Diagnostics`. Output appears in UEFN's Output Log window.
## Try It Yourself
**Challenge:** Modify the `OnBegin` function to make the trap more dynamic.
1. Instead of targeting the *first* player, make it target a *random* player.
2. Hint: You'll need to use the `GetRandomInt` function to pick a random index from the `AllPlayers` array.
3. If the list is empty, make sure your code doesn't crash (remember the `if` check!).
**Hint:**
```verse
# GetRandomInt(Min, Max) returns a random integer between Min and Max (inclusive).
# AllPlayers.Length gives the total count; subtract 1 for a valid last index.
RandomIndex : int = GetRandomInt(0, AllPlayers.Length - 1)
if (RandomPlayer := AllPlayers[RandomIndex]):
set KillerAgent = option{RandomPlayer}
Recap
OnBeginis the event that fires when your map transitions from Editor Mode to Running Mode. It's the "Game Start" whistle.- Variables are like logbooks or scoreboards that store data (like an agent reference) so your script can remember things.
@editablefields are the correct way to reference placed devices in Verse—drag them in from the UEFN Details panel instead of searching by name at runtime.- By using
OnBegin, you can set up complex logic (like targeting specific players) before the first player even moves, making your islands feel responsive and intelligent.
Now go build a trap that waits for no one.
References
- https://dev.epicgames.com/documentation/en-us/fortnite/persistent-player-statistics-in-unreal-editor-for-fortnite
- https://dev.epicgames.com/documentation/en-us/fortnite/talisman-environment-template-in-unreal-editor-for-fortnite
- https://dev.epicgames.com/documentation/en-us/fortnite/debugging-and-troubleshooting-in-verse
- https://dev.epicgames.com/documentation/en-us/fortnite/disappearing-platform-on-touch-using-verse-in-unreal-editor-for-fortnite
- https://dev.epicgames.com/documentation/en-us/fortnite/change-a-players-point-of-view-with-cameras-in-unreal-editor-for-fortnite
Verse source files
- 01-device.verse · device
- 02-fragment.verse · fragment
Turn this into a guided course
Add Runs when the device is started in a running game to your free study plan — we'll suggest related pages and stitch the lot into one compile-checked, self-guided lesson with worked examples and quizzes.
References
Original tutorial generated by Verse Island from the Verse/UEFN knowledge base, with references to the Epic Games sources above. Code is validated against the knowledge base.