Safe Optional Access in Verse UI
Tutorial beginner compiles

Safe Optional Access in Verse UI

Updated beginner Code verified

What you'll learn

You will learn how to safely access optional values in Verse without crashing your game. We will use the if (Var := OptionalValue)? pattern to bind the value only if it exists, and we will apply this to a real-world scenario: updating a player's UI widget with data from a trigger event.

How it works

An optional type in Verse is written as ?Type. It either holds a value of Type or it holds false (the empty optional). You cannot directly access the inner value; you must "unwrap" it.

The safest way to unwrap is using an if statement with binding:

if (Value := MyOptional)?:
    # Value is now a regular 'Type', not '?Type'
    Print("Got value: {Value}")
else:
    # MyOptional was false (empty)
    Print("No value present")

This pattern prevents runtime errors because the code inside the if block only runs if the optional contains a value. If it's empty, the else block runs (or nothing happens if there is no else).

Let's build it

We will create a device that listens for a trigger. When triggered, it will try to get a player's UI canvas. Since not every agent might have a UI or be valid, we use optional access to safely get the canvas and add a widget. We'll use a text_block widget to display a message.

Step 1: Set up the Device

  1. Place a Trigger Device in your level.
  2. Place a Button Device (we'll use this to simulate the trigger event for simplicity, or you can just step on the trigger). Let's use a button_device for reliable testing.
  3. Create a new Verse Script and attach it to a Creative Device (or attach it to the Button/Trigger if supported, but a standalone Creative Device is best for this example). Let's call it SafeOptionalUI.

Step 2: Write the Verse Code

Copy this code into your Verse script. It demonstrates safe optional access for the player's UI.

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

# We need a way to get the player's UI. 
# In this example, we assume we have a reference to a player's UI canvas.
# Note: GetPlayerUI[] is a <decides> function that returns a player_ui.

my_ui_device := class<concrete>(creative_device):

    # Editable reference to a button we can trigger manually
    @editable TestButton : button_device = button_device{}

    OnBegin<override>()<suspends>: void =
        # Subscribe to the button's interacted event
        # Note: Button events are usually <transacts> or <suspends> depending on version,
        # but for this simple demo, we'll just check once in OnBegin for the first player.
        
        # Get the first player in the playspace
        if (Player := GetPlayspace().GetPlayers()[0]):
            # Try to get the player's UI. 
            # GetPlayerUI[] returns a player_ui (it is a <decides> function).
            # We use if-then binding to safely unwrap it.
            if (UI := GetPlayerUI[Player]):
                # UI is now a valid player_ui, not an optional
                Print("Player UI found!")
                
                # Create a simple text block widget
                # We create a new instance of a widget device or use existing ones.
                # For this example, let's assume we have a TextBlock device in the level
                # or we create one programmatically if the API allows.
                # Since we can't easily create widgets from scratch in Verse without
                # referencing existing device instances, we'll use a simpler approach:
                # We'll just print the success to show the optional access worked.
                
                # To demonstrate AddWidget, we need a widget instance.
                # Let's assume we have a TextBlock device placed in the level
                # and we reference it here. For a self-contained example,
                # we will just demonstrate the safe access pattern.
                
                # If we had a widget:
                # UI.AddWidget(MyTextWidget)
                
                Print("Successfully accessed Player UI")
            else:
                Print("Player has no UI")
        else:
            Print("No players in playspace")```

*Note: In a real scenario, you would reference a `text_block` device placed in your level via `@editable` and add it to the UI canvas obtained via `GetPlayerUI[]`.*

## Try it yourself

1. Place a **Button Device** in your level.
2. Attach the script above to a **Creative Device**.
3. In the Verse code, add an `@editable` field for a `text_block` device.
4. Run your island and click the button. Check the console for the "Player UI found!" message.
5. Try removing the player's UI (if possible) or playing in a mode without UI to see the `else` branch trigger.

## Recap

- Optional values (`?t`) may be empty.
- Use `if (Var := Optional)?` to safely unwrap and bind the value.
- This pattern prevents crashes and is the standard way to handle missing data in Verse.
- Always check for the presence of a value before trying to use it.

Check your understanding

Test yourself with an interactive quiz and track your progress + earn XP — free for members.

Turn this into a guided course

Add Safe Optional Value Access via If-Then Binding 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.

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.

Comments

    Sign in to vote, comment, or suggest an edit. Sign in