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.


UEFN Verse: Tupla

Uma Tupla é um container que armazena de uma forma simples uma sequência de elementos que podem ser de tipos diferentes. Os elementos da Tupla podem ser acessados por um índice que indica a posição.

No exemplo abaixo, PersonData é uma Tupla com três elementos do tipo string, int e float

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

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

Uma das utilidades da Tupla é permitir que uma função retorne mais de uma valor. O tipo de retorno de uma função pode ser uma Tupla com vários elementos como mostra o código a seguir.

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)

    # Retorna esta tupla
    ( Name, ArmorLevel, Speed )

WarriorNames é um array de string que possui alguns nomes armazenados. A função GenerateWarriorData gera alguns valores aleatórios que são retornados dentro de uma Tupla.

Outra característica interessante da Tupla é que ela pode ser passada para uma função quando os parâmetros da função tem os tipos equivalentes aos elementos da Tupla. Isto será demonstrado no exemplo principal deste artigo.

Um elemento de uma Tupla pode ser um array ou outra Tupla. Minha sugestão é de não criar Tuplas complexas com muitos elementos porque o programador vai precisar checar o significado de cada elemento e isso pode provocar erros difíceis de encontrar. 

Ao invés de criar uma Tupla complexa, crie uma struct ou class com os nomes de campos bem definidos.

No dispositivo Verse de exemplo, será mostrado diferentes forma de chamar uma função com Tuplas. 

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 tuple_device clique no botão Create Empty.

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

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)

        # Retorna esta tupla
        ( Name, ArmorLevel, Speed )

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

A função ShowWarriorData() é chamada 3 vezes:

  • Na primeira vez, cada elemento da tupla é acessado pelo índice e passado como parâmetro. 
  • Na segunda vez, a Tupla é passado como parâmetro. Isto é permitido quando os tipos dos elementos da Tupla são equivalentes aos tipos dos parâmetros da função.
  • Na terceira vez, a Tupla resultante da função GenerateWarriorData() será passada como parâmetro.


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 tuple_device ao nível. Salve o nível e clique no botão Launch Session para carregar o nível no Fortnite.  

Após iniciar a partida no Fortnite, pressione a tecla Tab e selecione a aba Registro para visualizar o log com as mensagem escritas com os dados gerados.

terça-feira, 9 de setembro de 2025

UEFN Verse: Enum (enumeration)

The Enumeration (Enum) is used to create a new data type whose possible values ​​are restricted to the set of constants defined in the enumeration.

In the example below, difficulty is an Enumeration with five possible values.

difficulty := enum{Story, Easy, Normal, Hard, Expert}

To define a difficulty type constant that can be modified in the editor, do this:

@editable
Difficulty : difficulty = difficulty.Normal


An Enumeration can be closed or open. The difficulty Enumeration we created is closed because it's the default. A closed Enumeration cannot be modified after the island (map or experience) has been published in Fortnite, so it should only be used when you're sure the Enumeration won't change.

To create an open Enumeration, use the <open> specifier as shown in the code below which defines some states that will be used by an NPC guard:

guard_states := enum<open>{Idle, Patrolling, Searching, Attacking}


Let's create a device in UEFN to demonstrate the use of Enumeration. 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 enum_device and click the Create Empty button.

Copy the Verse code below into the enum_device file:

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

difficulty := enum{Story, Easy, Normal, Hard, Expert}

enum_device := class(creative_device):

    @editable
    Difficulty : difficulty = difficulty.Normal 

    var EnemyAttackModifier : float = 1.0

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

        case(Difficulty):
            difficulty.Story => 
                set EnemyAttackModifier = 0.5
                Print("Enemy Attack Modifier of 50% in Story Difficulty.")

            difficulty.Easy =>
                set EnemyAttackModifier = 0.75
                Print("Enemy Attack Modifier of 75% in Easy Difficulty.")

            difficulty.Normal =>
                set EnemyAttackModifier = 1.0
                Print("Enemy Attack Modifier of 100% in Normal Difficulty.")

            difficulty.Hard =>
                set EnemyAttackModifier = 1.25
                Print("Enemy Attack Modifier of 125% in Hard Difficulty.")

            difficulty.Expert =>
                set EnemyAttackModifier = 1.5
                Print("Enemy Attack Modifier of 150% in Expert Difficulty.")


This example will assign different values ​​to the EnemyAttackModifier variable depending on the difficulty selected in enum_device.

Note that the case does not contain the default block "_". This is not required when the Enumeration used in the case is closed and all Enumeration values ​​have code blocks.

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 enum_device to the level. Select the enum_device in the level and in the Details tab, click the Difficulty field dropdown to select one of the Enumeration values.



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 message written according to the selected difficulty.