domingo, 16 de novembro de 2025

UEFN Verse SG: Introduction to Scene Graph

This is the first in a series of articles related to the Scene Graph system in UEFN.

Epic Games and many developers have emphasized the importance of the Scene Graph system, but for some developers or newcomers to UEFN, the benefits of learning and using Scene Graph may not be so clear.

First of all, the Scene Graph system does not replace the Creative Device system that has been available in UEFN since its launch. Let's compare the two systems:

  • Creative Device System: This is a high-level system focused on gameplay programming that allows for the manipulation of devices.
  • Scene Graph System: This is a low-level system that allows the use of the Verse language to manipulate the entities that make up the scene and to program custom components.

Through Scene Graph, Epic Games is providing developers with new tools that expand the possibilities of what can be built in UEFN.

Epic Games has made it clear that the Verse language and the Scene Graph system will be the cornerstones of programming in Unreal Engine 6. UEFN is a great lab to practice these concepts before the release of Unreal Engine 6. 

The Scene Graph is a structure that represents the elements of a scene in a hierarchical way and has these three fundamental concepts:

  • Entity: It is a container where components are placed. An entity can also contain other entities.
  • Component: This is what gives life to an entity. An entity can contain several components to define its physical, visual, and behavioral aspects. New components can be programmed using the Verse language.
  • Prefab: It is used to group a hierarchy of entities and components into a class and store it as a project asset. Multiple instances of a Prefab can be added at the level, and the Prefab class can be used directly in Verse code.


In this article, we will look at a basic workflow that involves these three concepts. It is very important that these concepts are clear before delving deeper into the study of the Scene Graph.

The first step is to create an empty entity at the level. This is done from the Place Actors tab, which can be opened in the top Window menu.

In the category icons on the left, select Entities and drag the entity into the level.


In the Details tab, you'll see that the entity added to the level has a transform_component, which is used to define the entity's location within the level.


Click the +Component button to add more components. A list of available components will be displayed. Some component types are abstract and require you to choose a subclass. For example, select mesh_component.


The static meshes available as mesh_component are the basic shapes listed below. Select the cone.



Fortnite's Static Meshes and FAB assets are not compatible with Scene Graph in UEFN. This is an important and sometimes frustrating point for those starting out with Scene Graph.

To use custom Static Meshes, you need to import a 3D mesh file such as an .fbx or create one using the UEFN modeling tools.

Now let's add another mesh_component to the entity that was created. However, if you click on +Component you will see that the mesh_component no longer appears in the component list. This happens because an entity can only have one component of each type.

We will need to create a child entity to add the mesh_component to this new entity. In the Outliner tab, right-click on the entity that was created and select Add Entity > entity:


In the Details tab of the child entity, click the +Component button and select mesh_component > cube. This cube will be used as the tabletop, so change the Scale of the UP axis (green) to 0.1.


In the level editor, use the green arrow to position the tabletop on top of the cone:


The next step is to convert this hierarchy of entities and components into a Prefab. It will be stored as a project Asset. This will allow instances of this Prefab to be added at the level using the level editor or Verse code.

In the Outliner tab, right-click the parent entity and select Save As Prefab... :



On the next screen, enter a name for your Prefab. I chose Prefab_Table. Then click the Create entity Class button.


The Prefab editor will display our new Prefab for editing. Close the Prefab editor and access the Content Drawer to view the created Prefab asset. In my example, the UEFN editor created a folder with the same name as the project folder:


Drag and drop the Prefab within the level to create new instances:


In this article, we'll stop here. In the next articles, we'll look at Entities, Components, and Prefabs in more detail. We'll also learn how to program our own component using Verse.


Table of Contents Verse 


UEFN Verse SG: Introdução ao Scene Graph

Este é o primeiro de uma série de artigos relacionados ao sistema de Scene Graph no UEFN.

A Epic Games e muitos desenvolvedores tem ressaltado a importância do sistema de Scene Graph, mas para alguns desenvolvedores ou novatos no UEFN talvez não seja tão claro quais são os benefícios de aprender e utilizar o Scene Graph.

Em primeiro lugar o sistema de Scene Graph não substitui o sistema de Creative Device que está disponível no UEFN desde seu lançamento. Vamos comparar os dois sistemas:

  • Sistema de Creative Device: É um sistema de alto nível voltado para a programação de gameplay que permite a manipulação dos dispositivos.
  • Sistema de Scene Graph: É um sistema de baixo nível que permite o uso da linguagem Verse para manipular as entidades que compõem a cena e programar componentes personalizados.

Através do Scene Graph, a Epic Games está fornecendo para os desenvolvedores novas ferramentas que expandem as possibilidades do que pode ser construído no UEFN.

A Epic Games já deixou claro que a linguagem Verse e o sistema de Scene Graph serão os pilares da programação na Unreal Engine 6. O UEFN é um ótimo laboratório para praticar estes conceitos antes do lançamento da Unreal Engine 6. 

O Scene Graph é uma estrutura que representa os elementos da cena de uma forma hierárquica e possui estes três conceitos fundamentais:

  • Entidade: É um container onde são colocados os componentes. Uma Entidade também pode conter outras entidades.
  • Componente: Isto é o que dá vida à uma entidade. Uma entidade pode conter vários componentes para definir seus aspectos físicos, visuais e comportamentais. Novos componentes podem ser programados usando a linguagem Verse.
  • Prefab: É usado para agrupar uma hierarquia de entidades e componentes em uma classe e guardar como um Asset do projeto. É possível adicionar várias instâncias de um Prefab no nível e usar a classe do Prefab diretamente no código Verse.


Neste artigo veremos um workflow básico que envolve estes três conceitos. É muito importante que estes conceitos estejam bem claros antes de aprofundar no estudo do Scene Graph.

O primeiro passo é criar uma entidade vazia no nível. Isto é feito a partir da aba Place Actors que pode ser aberta no menu superior Window

Nos ícones de categorias na esquerda selecione Entities e arraste o entity para dentro do nível.


Veja na aba Details que a entidade que foi adicionada ao nível tem um transform_component que é usado para definir a localização da entidade no nível. 


Clique no botão +Component para adicionar outros componentes. Será exibida uma listagem dos componentes disponíveis. Alguns tipos de componentes são abstratos e é preciso escolher uma subclasse dele. Por exemplo, selecione o mesh_component.


As Static Meshes disponíveis como mesh_component são as formas básicas listadas abaixo. Selecione o cone.


As Static Meshes do Fortnite e os assets do FAB não são compatíveis com Scene Graph no UEFN. Este é um ponto importante e às vezes frustrante para quem está iniciando com Scene Graph.

Para usarmos Static Meshes customizadas é preciso importar um arquivo de malha 3d como .fbx ou criar um usando as ferramentas de modelagem do UEFN.

Agora vamos adicionar outro mesh_component à entidade que foi criada. Entretanto, se você clicar no +Component verá que o mesh_component não aparece mais na listagem de componentes. Isto acontece porque uma entidade só pode ter um componente de cada tipo. 

Será necessário criar uma entidade filha para adicionar o mesh_component nesta nova entidade. Na aba Outliner, clique com o botão direito na entidade que foi criada e selecione Add Entity > entity


Na aba Details da entidade filha, clique no botão +Component e selecione mesh_component > cube. Este cubo será usado como o tampo de uma mesa por isso altere o Scale do eixo UP (verde) para 0.1 :


No editor de nível, use a seta verde para posicionar o tampo da mesa no topo do cone:


O próximo passo é converter esta hierarquia de entidades e componentes em um Prefab. Ele será armazenada como um Asset do projeto. Isto permitirá a adição de instâncias deste Prefab no nível usando o editor de nível ou código Verse.

Na aba Outliner, clique com o botão direito na entidade pai e selecione Save As Prefab... :


Na tela seguinte, insira um nome para o seu Prefab. Eu escolhi Prefab_Table. Depois clique no botão Create entity Class.


O editor de Prefab será exibido com o nosso novo Prefab para edição. Feche o editor de Prefab e acesse o Content Drawer para visualizar o asset do Prefab que foi criado. No meu exemplo o editor UEFN criou uma pasta com o mesmo nome da pasta do projeto:


Arraste o Prefab e solte dentro do nível para criar novas instâncias:


Neste artigo vamos parar por aqui. Nos próximos artigos veremos as Entidades, Componentes e Prefab em mais detalhes. Também vamos aprender como programar nosso próprio componente usando Verse.

 

Sumário Verse 


segunda-feira, 29 de setembro de 2025

UEFN Verse: Creating events

Events are used as a form of communication between game elements. Creative devices have several events, and it's possible to create events on our devices using the verse language.

To create an event named MyEvent, do this: 

MyEvent<public>:event() = event(){}

The event can have parameters. To define an event with parameters, you need to specify the parameter types. The example below defines an event with a parameter of type int (integer):

MyEventWithParameter<public>:event(int) = event(int){}

To activate the event use the event's Signal() function:

MyEvent.Signal()

In an asynchronous context, use the event's Await() function to wait until the event is activated:

MyEvent.Await()

At the time of writing, the event class does not have the subscribable interface. This means that it is not possible to register a function to be called when the event is activated.

Maybe this is a strategy by Epic Games to get programmers to adapt to concurrent programming using Await().

Let's do an example to illustrate the use of events. We'll create a device named trigger_group_device that has an array of trigger_device.

This device will have an event called AllTriggersActivated that will activate when all trigger_device in the array are activated. It's a simple implementation that assumes each trigger_device can only be activated once.

Open Verse Explorer, right-click on the project name and choose the Add new Verse file to project option.

In Device Name put trigger_group_device and click the Create Empty button.

Copy the Verse code below into the trigger_group_device file:

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

trigger_group_device := class(creative_device):

    @editable
    TriggerGroup : []trigger_device = array{}

    var NumberOfTriggers : int = 0 

    var TriggersActivated : int = 0 

    # Creating the event
    AllTriggersActivated<public>:event(?agent) = event(?agent){}

    OnBegin<override>()<suspends>:void=

        set NumberOfTriggers = TriggerGroup.Length

        for (Trigger : TriggerGroup):
            Trigger.TriggeredEvent.Subscribe(OnTriggerActivated)


    OnTriggerActivated( MaybeAgent:?agent ):void=

        set TriggersActivated += 1

        if (TriggersActivated = NumberOfTriggers):

            # Activating the event
            AllTriggersActivated.Signal(MaybeAgent)

The trigger_device has the TriggeredEvent event. In the OnBegin function, the for loop is used to iterate through the array and register the OnTriggerActivated() function in the TriggeredEvent event of each trigger.

When the player activates a trigger, the OnTriggerActivated() function is called, which increments the activated trigger count and compares it to the total number of triggers. The AllTriggersActivated event is activated when all triggers are activated.

Save the file and compile the Verse code using the Verse > Build Verse Code option from the UEFN menu.

Let's create another device that will wait for the AllTriggersActivated event to be activated to spawn an item using the Item Spawner device.

In the Verse Explorer, right-click on the project name and choose the Add new Verse file to project option.

In Device Name put event_device and click the Create Empty button.

Copy the Verse code below into the event_device file:

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

event_device := class(creative_device):

    @editable 
    TriggerGroupDevice : trigger_group_device = trigger_group_device{}

    @editable
    ItemSpawnerDevice : item_spawner_device = item_spawner_device{}

    OnBegin<override>()<suspends>:void=

        TriggerGroupDevice.AllTriggersActivated.Await()
        ItemSpawnerDevice.SpawnItem()

The OnBegin() function uses the Await() function of the AllTriggersActivated event to wait until it is activated. After activation, the SpawnItem() function of the ItemSpawnerDevice will be executed. 

Save the file and compile the Verse code using the Verse > Build Verse Code option from the UEFN menu.

Access the Content Drawer and add the trigger_group_device and event_device to the level.

Add four Trigger Device to the level. Select all Trigger Device and in the Details tab, look for the Times Can Trigger property. Check this property and keep the value 1 so that each Trigger Device is activated only once.


Add an Item Spawner to the level. It will be used to generate a reward for the player after activating all Trigger Device. In the Details tab, uncheck the Spawn Item on Timer and Respawn Item on Timer properties.

To select the item that will be spawned, click the + button in the Item List row. Under Pickup to Spawn, select the item that will be spawned. I used the Mythic Goldfish. 


Select the trigger_group_device in the level. In the Details tab, add 4 elements to the TriggerGroup array. For each element, select a Trigger Device instance.


Select the event_device level. In the Details tab, add references to the trigger group device and the Item Spawner device.


Save the level and click the Launch Session button to load the level into Fortnite. Pass over all triggers to spawn the item in the Item Spawner.



UEFN Verse: Criando eventos

Eventos são usados como uma forma de comunicação entre os elementos de um jogo. Os dispositivos criativos possuem diversos eventos e é possível criar eventos em nossos dispositivos usando a linguagem verse. 

Para criar um evento com o nome MyEvent, faça assim:

MyEvent<public>:event() = event(){}

O evento pode ter parâmetros. Para definir um evento com parâmetros é preciso informar os tipos dos parâmetros. O exemplo abaixo define um evento com um parâmetro do tipo int (inteiro):

MyEventWithParameter<public>:event(int) = event(int){}

Para ativar o evento use a função Signal() do evento:

MyEvent.Signal()

Em um contexto assíncrono, use a função Await() do evento para esperar até que o evento seja ativado:

MyEvent.Await()

No momento da escrita deste artigo, a classe event não tem a interface subscribable. Isto significa que não é possível registrar uma função para ser chamada quando o evento for ativado. 

Talvez isto seja uma estratégia da Epic Games para que os programadores se adaptem à programação concorrente usando o Await().

Vamos fazer um exemplo para ilustrar o uso de eventos. Será criado um dispositivo com o nome trigger_group_device que possui um array de trigger_device

Este dispositivo possuirá um evento chamado AllTriggersActivated que será ativado quando todas as trigger_device do array forem ativadas. É uma implementação simples que assume que cada trigger_device só pode ser ativada uma vez.

Abra o Verse Explorer, clique com o botão-direito no nome do projeto e escolha a opção Add new Verse file to project.

Em Device Name coloque trigger_group_device  clique no botão Create Empty.

Copie o código Verse abaixo para o dispositivo trigger_group_device:

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

trigger_group_device := class(creative_device):

    @editable
    TriggerGroup : []trigger_device = array{}

    var NumberOfTriggers : int = 0 

    var TriggersActivated : int = 0 

    # Criando o evento
    AllTriggersActivated<public>:event(?agent) = event(?agent){}

    OnBegin<override>()<suspends>:void=

        set NumberOfTriggers = TriggerGroup.Length

        for (Trigger : TriggerGroup):
            Trigger.TriggeredEvent.Subscribe(OnTriggerActivated)


    OnTriggerActivated( MaybeAgent:?agent ):void=

        set TriggersActivated += 1

        if (TriggersActivated = NumberOfTriggers):

            # Ativando o evento
            AllTriggersActivated.Signal(MaybeAgent)

O trigger_device possui o evento TriggeredEvent. Na função OnBegin é usado o laço for para iterar no array e registrar a função OnTriggerActivated() no evento TriggeredEvent de cada trigger.

Quando o jogador ativar uma trigger, a função OnTriggerActivated() será chamada que aumenta o contador de triggers ativadas e compara com o numero total de triggers. O evento AllTriggersActivated é ativado quando todas as triggers forem ativadas. 

Salve o arquivo e compile o código Verse usando a opção Verse > Build Verse Code do menu do UEFN.

Vamos criar outro dispositivo que irá aguardar a ativação do evento  AllTriggersActivated para gerar um item usando o Item Spawner device.

NVerse Explorer, clique com o botão-direito no nome do projeto e escolha a opção Add new Verse file to project.

Em Device Name coloque event_device clique no botão Create Empty.

Copie o código Verse abaixo para o dispositivo event_device:

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

event_device := class(creative_device):

    @editable 
    TriggerGroupDevice : trigger_group_device = trigger_group_device{}

    @editable
    ItemSpawnerDevice : item_spawner_device = item_spawner_device{}

    OnBegin<override>()<suspends>:void=

        TriggerGroupDevice.AllTriggersActivated.Await()
        ItemSpawnerDevice.SpawnItem()

Na função OnBegin() é usado a função Await() do evento AllTriggersActivated que espera até sua ativação. Após a ativação, será executada a função SpawnItem() do ItemSpawnerDevice

Salve o arquivo e compile o código Verse usando a opção Verse > Build Verse Code do menu do UEFN. 

Acesse o Content Drawer e adicione os dispositivos trigger_group_device e event_device ao nível. 

Adicione quatro Trigger Device no nível. Selecione os Trigger Device e na aba Details procure pela propriedade Times Can Trigger. Marque esta propriedade e mantenha o valor 1 para que cada Trigger Device seja ativado somente uma vez.


Adicione um Item Spawner no nível. Ele será usado para gerar uma recompensa para o jogador depois que ele ativar todas os Trigger Device. Na aba Details, desmarque as propriedades Spawn Item on Timer e Respawn Item on Timer.

Para definir o item que será gerado, clique no botão + na linha do Item List. Em Pickup to Spawn, selecione o item que será gerado. Eu usei o Mythic Goldfish. 


Selecione o trigger_group_device no nível. Na aba Details adicione 4 elementos no array TriggerGroup. Para cada elemento, selecione uma instância de Trigger Device.


Selecione o event_device no nível. Na aba Details adicione as referências do trigger group device e do Item Spawner device.


Salve o nível e clique no botão Launch Session para carregar o nível no Fortnite. Passe por cima de todas as triggers para gerar o item no Item Spawner.



terça-feira, 23 de setembro de 2025

UEFN Verse: Defer (Control Flow)

Defer is a control flow expression that executes a block of code only after the current scope exits. For example, Defer is used in a function so that its code block will only execute after the function completes or is canceled.

Defer is useful for resetting variables and cleaning up used resources. It's also a good option for placing code that needs to be executed at the end of a long function with many different termination locations. This way, the code doesn't need to be repeated everywhere.

In the example below, PropMove is a creative_prop and InitialTransform is a transform (position, rotation and scale).

defer:
    if ( PropToMove.TeleportTo[ InitialTransform ] ) {}

The TeleportTo function doesn't execute immediately. It only executes when the current scope exits. The goal is to return the creative prop to its initial position.

The if expression is necessary because the TeleportTo function is a failable expression.

Let's create an example to illustrate this use of the Defer expression. In this example, a creative prop will move toward the player. The player must activate a trigger to stop the pursuit. The creative prop will return to its starting position when deactivated.

In any UEFN project, open Verse Explorer, right-click on the project name and choose the Add new Verse file to project option.

In Device Name put defer_device and click the Create Empty button.

Copy the Verse code below into the defer_device file:

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

defer_device := class(creative_device):

    @editable
    PropToMove : creative_prop = creative_prop{}

    @editable
    Trigger : trigger_device = trigger_device{}

    OnBegin<override>()<suspends>:void=

        race:
            FollowPlayer()
            Trigger.TriggeredEvent.Await()

    FollowPlayer()<suspends>:void=

        if:
            Player := GetPlayspace().GetPlayers()[0]
            Character := Player.GetFortCharacter[]
        then:
            InitialTransform := PropToMove.GetTransform()

            PropRotation := PropToMove.GetTransform().Rotation

            defer:
                # Return to starting position when exiting scope (cancel or complete)
                if ( PropToMove.TeleportTo[ InitialTransform ] ) {}

            loop:
                NewTranslation := Character.GetTransform().Translation
                PropToMove.MoveTo( NewTranslation, PropRotation, 5.0 )

The OnBegin function has only one race expression with two concurrent expressions. When the trigger is activated, the FollowPlayer() function will be canceled and the expression associated with defer will be executed.

In the FollowPlayer() function, we need to get the reference to the first player's FortCharacter instance to get its current position. The expression GetPlayspace().GetPlayers() returns an array with the players. Since we only want the first player, the index [0] was used to get the first element of the array returned by the GetPlayers() function.

Save the file and compile the Verse code using the Verse > Build Verse Code option from the UEFN menu.

Access the Content Drawer and add our defer_device to the level. Add a Trigger Device away from the player's starting position. We need a creative_prop that will be used to track the player. In my example, I used Gnome02, but you can choose any.

Select the defer_device in the level. In the Details tab, add the creative prop and trigger references.



Save the level and click the Launch Session button to load it into Fortnite. Watch the creative prop move toward your character. Step over the trigger to stop the chase and return the creative prop to its starting position.

UEFN Verse: Defer (controle de fluxo)

Defer é uma expressão de controle de fluxo que executa um bloco de código somente depois que o escopo atual encerrar. Por exemplo, o Defer é usado em uma função então seu bloco de código só será executado depois que a função concluir ou for cancelada.

O Defer é útil para resetar variáveis e limpar recursos que foram usados. Também é uma boa opção para colocar códigos que precisam ser executados no final de uma função grande que possui muitos locais diferentes de finalização. Dessa forma os códigos não precisam ser repetidos em todos os locais.

No exemplo abaixo, PropMove é um creative_prop e InitialTransform é um transform (posição, rotação e escala).

defer:
    if ( PropToMove.TeleportTo[ InitialTransform ] ) {}

A função TeleportTo não é executada imediatamente. Ela só será executada quando o escopo atual encerrar. O objetivo é voltar o creative prop à sua posição inicial.

A expressão if é necessária porque a função TeleportTo é uma expressão falível.

Vamos criar um exemplo para ilustrar este uso da expressão Defer. Neste exemplo um creative prop se moverá em direção ao jogador. O jogador precisa ativar uma trigger para parar a perseguição. O creative prop voltará a sua posição inicial quando for desativado. 

Em qualquer projeto UEFN, abra o Verse Explorer, clique com o botão-direito no nome do projeto e escolha a opção Add new Verse file to project.

Em Device Name coloque defer_device clique no botão Create Empty.

Copie o código Verse abaixo para o dispositivo defer_device:

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

defer_device := class(creative_device):

    @editable
    PropToMove : creative_prop = creative_prop{}

    @editable
    Trigger : trigger_device = trigger_device{}

    OnBegin<override>()<suspends>:void=

        race:
            FollowPlayer()
            Trigger.TriggeredEvent.Await()

    FollowPlayer()<suspends>:void=

        if:
            Player := GetPlayspace().GetPlayers()[0]
            Character := Player.GetFortCharacter[]
        then:
            InitialTransform := PropToMove.GetTransform()

            PropRotation := PropToMove.GetTransform().Rotation

            defer:
                # Retornar à posição inicial ao sair do escopo (cancelar ou concluir)
                if ( PropToMove.TeleportTo[ InitialTransform ] ) {}

            loop:
                NewTranslation := Character.GetTransform().Translation
                PropToMove.MoveTo( NewTranslation, PropRotation, 5.0 )

A função OnBegin possui apenas uma expressão race com duas expressões concorrentes. Quando o trigger for ativado, a função FollowPlayer() será cancelada e a expressão associada ao defer será executada. 

Na função FollowPlayer() precisamos obter a referência para a instância de FortCharacter do primeiro jogador para pegar a sua posição atual. A expressão GetPlayspace().GetPlayers() retorna um array com os jogadores. Como queremos somente o primeiro jogador, a indexação [0] foi usada para pegar o primeiro elemento do array que retorna da função GetPlayers().

Salve o arquivo e compile o código Verse usando a opção Verse > Build Verse Code do menu do UEFN. 

Acesse o Content Drawer e adicione o dispositivo defer_device ao nível. Adicione um Trigger Device longe da posição inicial do jogador. Precisamos de um creative_prop que será usado para perseguir o jogador. No meu exemplo eu usei o Gnome02, mas você pode escolher qualquer um.

Selecione o defer_device no nível. Na aba Details adicione as referências do creative prop e do trigger.



Salve o nível e clique no botão Launch Session para carregar o nível no Fortnite. Observe o creative prop se movendo em sua direção. Passe por cima da trigger para parar a perseguição e retornar o creative prop à sua posição inicial.

terça-feira, 16 de setembro de 2025

UEFN Verse: Tuple

A Tuple is a container that stores a sequence of elements that can be of different types in a simple way. Tuple elements can be accessed by an index that indicates their position.

In the example below, PersonData is a Tuple with three elements of type string, int and float. 

PersonData : tuple(string, int, float) = ("Romero", 47, 1.80)

Print("Name: { PersonData(0) }")
Print("Age: { PersonData(1) }")
Print("Height: { PersonData(2) }")

One of the uses of Tuple is that it allows a function to return more than one value. A function's return type can be a Tuple with multiple elements, as shown in the following code.

GenerateWarriorData(): tuple(string, int, float) =

    var Name : string = ""

    if( RandomName := WarriorNames[ GetRandomInt(0, WarriorNames.Length - 1) ] ):
        set Name = RandomName 
	
    ArmorLevel := GetRandomInt(2,6)

    Speed := GetRandomFloat(5.0, 10.0)

    # Returns this tuple
    ( Name, ArmorLevel, Speed )

WarriorNames is a string array containing some names. The GenerateWarriorData function generates some random values ​​that are returned as a Tuple.

Another interesting feature of the Tuple is that it can be passed to a function when the function's parameters have types equivalent to the Tuple's elements. This will be demonstrated in the main example of this article.

An element of a tuple can be an array or another Tuple. My suggestion is to avoid creating complex Tuples with many elements because the programmer will need to check the meaning of each element, which can lead to difficult-to-find errors.

Instead of creating a complex Tuple, create a struct or class with well-defined field names.

In the example Verse device, I will show different ways to call a function with Tuples. 

In any UEFN project, open Verse Explorer, right-click on the project name and choose the Add new Verse file to project option.

In Device Name put tuple_device and click the Create Empty button.

Copy the Verse code below into the tuple_device file:

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

tuple_device := class(creative_device):

    WarriorNames : []string = array{"Archon", "Aryss", "Alarik", "Dessloch", 
                   "Cryss", "Nikita", "Drimacus", "Rhea", "Raynor", "Kira"}

    OnBegin<override>()<suspends>:void=
        
        var Warrior1 : tuple(string, int, float) = ("", 0, 0.0)

        set Warrior1 = GenerateWarriorData()

        Warrior2 := GenerateWarriorData()

        ShowWarriorData( Warrior1(0), Warrior1(1), Warrior1(2) )

        ShowWarriorData( Warrior2 )

        ShowWarriorData( GenerateWarriorData() )

    GenerateWarriorData(): tuple(string, int, float) =

        var Name : string = ""

        if( RandomName := WarriorNames[ GetRandomInt(0, WarriorNames.Length - 1) ] ):
            set Name = RandomName 
        
        ArmorLevel := GetRandomInt(2,6)

        Speed := GetRandomFloat(5.0, 10.0)

        # Returns this tuple
        ( Name, ArmorLevel, Speed )

    ShowWarriorData(Name:string, ArmorLevel:int, Speed:float):void =
        Print("Name: {Name} | Armor Level: {ArmorLevel} | Speed: {Speed}")

The ShowWarriorData() function is called 3 times:

  • The first time, each element of the Tuple is accessed by index and passed as a parameter. 
  • The second time, the Tuple is passed as a parameter. This is allowed when the types of the Tuple's elements are equivalent to the types of the function's parameters.
  • The third time, the Tuple resulting from the GenerateWarriorData() function will be passed as a parameter.


Save the file and compile the Verse code using the Verse > Build Verse Code option from the UEFN menu.

Access the Content Drawer and add the tuple_device to the level. Save the level and click the Launch Session button to load it into Fortnite. 

After starting the Fortnite session, press the Tab key and select the Log tab to view the log with the messages written with the generated data.