quarta-feira, 27 de maio de 2026

UEFN Verse: fort_character interface

The fort_character interface is used to define the capabilities of characters in Fortnite. It is associated with the character’s physical attributes and actions, such as health, shield, jumping, and crouching.

To better understand fort_character, let’s compare it with the agent class:

  • agent: Represents the entity controlling the character, which can be a human player or an NPC. It has an identifier (id) that persists throughout the game session. It can be thought of as the brain.
  • fort_characterRepresents the agent within the game world. It can be thought of as the body of the agent. When a player is eliminated, the fort_character is destroyed, but the agent instance remains active. When entering a new match, a new fort_character is created and associated with the existing agent.


This interface inherits from and implements several other interfaces, including healthful, damageable, healable, shieldable, positional, game_action_instigator, and game_action_causer. It serves as the main interface for characters, since a fort_character instance provides access to the methods defined by all of these interfaces.

Tip: When looking through the documentation or the Fortnite.digest file for methods available in fort_character, you will only find the methods defined directly in that interface. However, all methods from the interfaces mentioned earlier are also accessible through fort_character. For example, the SetHealth() method belongs to the healthful interface and can be called from fort_character.


You can use the fort_character interface to modify health and shield, as well as determine whether the character is jumping, crouching, on the ground, in water, or in the air. There are many available features. 

To use the fort_character interface, the following module must be added:

using { /Fortnite.com/Characters }


This module adds an extension method to the agent class that returns the associated fort_character instance:

if( FortCharacter := Agent.GetFortCharacter[] ):


It is also possible to retrieve the agent associated with a fort_character, if one exists:

if ( Agent := FortCharacter.GetAgent[] ):


The example below demonstrates how to increase the health of a fort_character by 10:

CurrentHealth := FortCharacter.GetHealth()
FortCharacter.SetHealth( CurrentHealth + 10 )


As a practical example of using fort_character, we will create a device that references a volume_device. The device can restore the health and shield of agents located inside the referenced volume and provides several configuration options.

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

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

Copy the Verse code below into the recharger_device file:

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

recharger_device := class(creative_device):

    @editable
    VolumeDevice : volume_device = volume_device{}

    @editable
    TimeInterval : float = 1.0

    @editable
    HealthRegenAmount : float = 10.0;
    
    @editable
    ShieldRegenAmount : float = 10.0;

    @editable
    IsHealthRecharger : logic = true;

    @editable
    IsShieldRecharger : logic = true;

    var AgentsInVolume : []agent = array{}

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

        loop: 
            Sleep(TimeInterval)

            set AgentsInVolume = VolumeDevice.GetAgentsInVolume()

            if(AgentsInVolume.Length > 0):

              for (Agent : AgentsInVolume):
                if(FortCharacter := Agent.GetFortCharacter[]):
                  if(IsHealthRecharger?):
                    CurrentHealth := FortCharacter.GetHealth()
                    FortCharacter.SetHealth(CurrentHealth + HealthRegenAmount)

                  if(IsShieldRecharger?):
                    CurrentShield := FortCharacter.GetShield()
                    FortCharacter.SetShield(CurrentShield + ShieldRegenAmount)


The device runs a loop every TimeInterval, which defaults to 1 second. On each iteration, it retrieves an array of agents inside the volume. For each agent, health and shield are increased if those options are enabled.

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

Access the Content Drawer and add the recharger_device to the level. Then add a Volume Device and check the Visible in Game option.


Select the recharger_device in the level. In the Details panel, assign the reference to the Volume Device. You can also configure the device to restore only health or shield, as well as adjust the recharge amount and time interval.



To make testing easier, reduce the player's starting health. In the Outliner panel, select Island Settings. In the Details panel, search for Health and set Starting Health Percentage to 20%.


Save the level and click Launch Session to load it in Fortnite. Move the character into the volume to restore health and shield.


UEFN Verse: Interface fort_character

A interface fort_character é usada para definir as capacidades dos personagens no Fortnite. Ela está relacionada aos atributos e ações do corpo do personagem, como atributos como health (saúde) e shield (escudo), além de ações como pular e agachar.

Para entender o fort_character vamos compará-lo à classe agent:

  • agent: Representa quem está jogando, que pode ser um jogador humano ou NPC. Possui uma identificação (id) que é mantida durante a sessão de jogo. É como se fosse o cérebro.
  • fort_character: Representa o agent dentro do mundo do jogo. É como se fosse o corpo do agent. Quando um jogador é eliminado, o fort_character é descartado, mas a instância de agent continua ativa. Ao entrar em uma nova partida, um novo fort_character é gerado e associado ao agent existente.


Esta interface herda e implementa várias outras interfaces, como 
healthful, damageable, healable, shieldable, positional, game_action_instigator, game_action_causer. Ela funciona como uma interface principal usada pelos personagens, pois uma instância de fort_character permite acessar os métodos de todas essas interfaces.

Dica: Ao procurar na documentação ou no arquivo Fortnite.digest os métodos disponíveis na interface fort_character, você verá apenas os métodos definidos diretamente em fort_character. Contudo, todos os métodos das interfaces mencionadas anteriormente também estão disponíveis no fort_character. Por exemplo, o método SetHealth() pertence à interface healthful e está disponível em fort_character.


Você pode usar a interface fort_character para modificar o health e shield, além de verificar se o personagem está pulando, agachado, no chão, na água ou no ar. Existem muitas funcionalidades disponíveis. 

Para usar a interface fort_character, é necessário adicionar este módulo:

using { /Fortnite.com/Characters }


Este módulo adiciona um método de extensão à classe agent para obter a instância de fort_character:

if( FortCharacter := Agent.GetFortCharacter[] ):


Também é possível obter a referência do agent associado ao fort_character, caso exista:

if ( Agent := FortCharacter.GetAgent[] ):


O exemplo abaixo mostra como aumentar o health de um fort_character em 10:

CurrentHealth := FortCharacter.GetHealth()
FortCharacter.SetHealth( CurrentHealth + 10 )


Como exemplo prático de fort_character vamos criar um dispositivo que referencia um volume_device. Este dispositivo pode recuperar o health e shield dos agentes que estiverem dentro do volume referenciado. Ele também terá várias opções de configuração. 

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

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

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

recharger_device := class(creative_device):

    @editable
    VolumeDevice : volume_device = volume_device{}

    @editable
    TimeInterval : float = 1.0

    @editable
    HealthRegenAmount : float = 10.0;
    
    @editable
    ShieldRegenAmount : float = 10.0;

    @editable
    IsHealthRecharger : logic = true;

    @editable
    IsShieldRecharger : logic = true;

    var AgentsInVolume : []agent = array{}

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

        loop: 
            Sleep(TimeInterval)

            set AgentsInVolume = VolumeDevice.GetAgentsInVolume()

            if(AgentsInVolume.Length > 0):

              for (Agent : AgentsInVolume):
                if(FortCharacter := Agent.GetFortCharacter[]):
                  if(IsHealthRecharger?):
                    CurrentHealth := FortCharacter.GetHealth()
                    FortCharacter.SetHealth(CurrentHealth + HealthRegenAmount)

                  if(IsShieldRecharger?):
                    CurrentShield := FortCharacter.GetShield()
                    FortCharacter.SetShield(CurrentShield + ShieldRegenAmount)


O dispositivo mantém um loop executado a cada TimeInterval, que por padrão é 1 segundo. A cada iteração do loop, é obtido um array de agentes que estão dentro do volume. Para cada agente, o health e shield são aumentados, caso estejam habilitados.

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

Acesse o Content Drawer e adicione o dispositivo recharger_device ao nível. Em seguida, adicione também um Volume Device e marque a propriedade Visible in Game.


Selecione o recharger_device no nível. Na aba Details, selecione a referência ao Volume Device.  Podemos configurar o dispositivo para recarregar apenas health ou shield, além de modificar o intervalo de tempo e a quantidade recarregada.



Para facilitar o teste do dispositivo, vamos diminuir o health inicial do jogador. Na aba Outliner, selecione o Island Settings. Na aba Details, pesquise por Health. Em Starting Health Percentage defina 20%


Salve o nível e clique no botão Launch Session para carregá-lo no Fortnite. Mova o personagem para dentro do volume para recarregar health e shield.



sexta-feira, 17 de abril de 2026

UEFN Verse: agent and player classes

In this article, I will cover the agent and player classes, as well as review the concepts of inheritance and casting.

The agent class is a subclass of entity. It represents entities that act in the game, which can be NPCs or players.

The player class is a subclass of agent. It represents a human player in the game.

According to the concepts of inheritance, a subclass inherits the properties of its superclass (parent class). It is as if it accumulates the types of its superclasses.

For example, an instance of the player class is also an agent and an entity. Therefore, it can be referenced by a field whose type is a superclass, such as agent. 

In UEFN, interactions with devices are performed by agents, which can be NPCs or players. To determine whether the agent that interacted with a device is a player, we can use casting to convert a reference of type agent to player. If the cast succeeds, the referenced instance is a player.
HandleItemPickedUp(Agent:agent):void=
    if ( Player := player[Agent] ):

After casting, the player reference allows access to fields and methods that are specific to the player class.

To see casting in action, we will create a device that references a trigger_device. When the trigger is activated, we use casting to check whether it was triggered by a player or an NPC. If it is a player, a green light turns on; otherwise, a red light turns on.

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

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

Copy the Verse code below into the agent_check_device file:

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

agent_check_device := class(creative_device):

    @editable
    TriggerDevice : trigger_device = trigger_device{}

    @editable
    GreenLight : customizable_light_device = customizable_light_device{}

    @editable
    RedLight : customizable_light_device = customizable_light_device{}

    OnBegin<override>()<suspends>:void =
        TriggerDevice.TriggeredEvent.Subscribe(OnTriggered)

    OnTriggered(MaybeAgent : ?agent) : void =
        if (Agent := MaybeAgent?):
            GreenLight.TurnOff()
            RedLight.TurnOff()

            if (Player := player[Agent]):
                GreenLight.TurnOn()
            else:
                RedLight.TurnOn()

The agent_check_device contains one trigger_device and two customizable_light_device.

In the OnTriggered function, the parameter is of type ?agent (option agent), since the TriggerDevice can be triggered by Verse code without any agent interaction. First, we check if it was triggered by an agent, and then determine whether the agent is a player or an NPC.

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

Acess the Content Drawer e add the agent_check_device to the level. Then add one Trigger Device, two Customizable Light Devices and one Wildlife Spawner Device

Select the Trigger Device at the level and check the option Triggered by Creatures.

Select one of the Customizable Light Devices, rename it to RedLight, set Light Color to red, and uncheck Initial State so the light starts off. Then rename the other light device to GreenLight and apply similar settings using green.


Select the agent_check_device in the level. In the Details panel, select the references to the devices added to the level.


We will use the Wildlife Spawner Device to spawn creatures in the level that can activate the Trigger Device when they pass over it. Select the device and, in Type, choose Random to spawn different types of creatures. Set Spawn Count to 10.


Save the level and click Launch Session to load it in Fortnite. Walk over the Trigger Device to activate the green light. Then try to lure a creature to walk over it and activate the red light.


UEFN Verse: Classes agent e player

Neste artigo, vou falar sobre as classes agent e player, além de revisar os conceitos de herança e casting.

A classe agent é uma subclasse de entity. Ela representa entidades que atuam  no jogo, podendo ser NPCs ou jogadores.

A classe player é uma subclasse de agent. Representa um jogador humano que está na partida.

Conforme os conceitos de herança, uma subclasse herda as propriedades de sua superclasse (classe pai). É como se acumulasse os tipos de suas superclasses. 

Por exemplo, uma instância da classe player também é um agent e é uma entity. Por isso, ela também pode ser referenciada por um campo cujo tipo seja o de uma superclasse, como agent

No UEFN, as interações com dispositivos são realizadas por agentes, que podem ser NPCs ou jogadores. Para verificar se o agente que interagiu com o dispositivo é um jogador, podemos usar casting para tentar converter a referência do tipo agent para uma referência do tipo player. Se o casting for bem-sucedido, significa que a instância referenciada é do tipo player.
HandleItemPickedUp(Agent:agent):void=
    if ( Player := player[Agent] ):

Após o casting, a referência do tipo player permitirá acessar os campos e métodos que pertencem apenas à classe player.

Para ver o casting em ação, vamos criar um dispositivo que referencia um trigger_device. Quando o trigger for acionado, vamos usar casting para verificar se foi um player ou um NPC que o ativou. Se for um jogador, uma luz verde será ligada. Se for um NPC, uma luz vermelha será ligada.

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

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

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

agent_check_device := class(creative_device):

    @editable
    TriggerDevice : trigger_device = trigger_device{}

    @editable
    GreenLight : customizable_light_device = customizable_light_device{}

    @editable
    RedLight : customizable_light_device = customizable_light_device{}

    OnBegin<override>()<suspends>:void =
        TriggerDevice.TriggeredEvent.Subscribe(OnTriggered)

    OnTriggered(MaybeAgent : ?agent) : void =
        if (Agent := MaybeAgent?):
            GreenLight.TurnOff()
            RedLight.TurnOff()

            if (Player := player[Agent]):
                GreenLight.TurnOn()
            else:
                RedLight.TurnOn()

O dispositivo agent_check_device possui um trigger_device e dois customizable_light_device

Na função OnTriggered, o parâmetro é do tipo ?agent (option agent), pois o TriggerDevice pode ser acionado por código Verse sem a interação de um agente. Primeiro, é verificado se o TriggerDevice foi acionado por um agente e, em seguida, é testado se o agente é um player ou NPC.

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

Acesse o Content Drawer e adicione o dispositivo agent_check_device ao nível. Em seguida, adicione também um Trigger Device, dois Customizable Light Devices e um Wildlife Spawner Device

Selecione o Trigger Device no nível e marque a opção Triggered by Creatures.

Selecione um dos Customizable Light Devices, renomeie para RedLight, escolha uma cor vermelha em Light Color e desmarque a opção Initial State para que a luz comece desligada. Renomeie o outro Light Device para GreenLight e faça os ajustes semelhantes usando a cor verde.


Selecione o agent_check_device no nível. Na aba Details, selecione as referências dos dispositivos adicionados ao nível.


Vamos usar o Wildlife Spawner Device para gerar criaturas no nível que poderão ativar o Trigger Device ao passarem sobre ele. Selecione o dispositivo e, em Type, escolha Random para que apareçam tipos diferentes de criaturas. Em Spawn Count, defina 10.


Salve o nível e clique no botão Launch Session para carregá-lo no Fortnite. Passe sobre o Trigger Device para ativar a luz verde. Tente atrair uma criatura para que ela passe sobre o Trigger Device e ative a luz vermelha.



domingo, 29 de março de 2026

UEFN Verse: Logging and Log channel

Log messages can help identify issues in your Verse code. These messages can be viewed in the in-game log tab and in the UEFN Output Log window. 

Logging in Verse requires two classes: log and log_channel.

The log_channel is used only to identify the source of the message. Its name is added to the beginning of the message. 

You need to create a subclass of log_channel at the module scope, that is, outside of classes or functions. The code below shows an example of a log_channel

log_general := class(log_channel){}

The next step is to create an instance of the log class inside a class or function, specifying the log_channel to be used:

LoggerGeneral:log = log{Channel:=log_general}

There are five log levels used to categorize messages: Debug, Verbose, Normal, Warning and Error.

Logs with Debug and Verbose levels appear only in the in-game log tab. They do not appear in the UEFN Output Log.

Logs with Warning and Error levels are displayed in different colors to draw attention.

A default log level can be defined when the log is created: 

LoggerGeneral:log = log{Channel:=log_general, DefaultLevel:=log_level.Warning}

To write to the log, use the Print function of the log class:

LoggerGeneral.Print("Experience started")

You can pass the log level as a parameter:

LoggerGeneral.Print("Data not found", ?Level := log_level.Error)

Another useful piece of information for debugging is the Call Stack, which shows the sequence of function calls leading to the current point in the code. Use the PrintCallStack function from the log class to log the Call Stack. 

LoggerGeneral.PrintCallStack()

To illustrate the use of logging, we will create a device that uses two logs. One will be used for general system messages, and the other for logging messages when buttons are pressed by the player. Different log levels will be used.

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

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

Copy the Verse code below into the log_example_device file:

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

log_general := class(log_channel){}
log_buttons := class(log_channel){}

log_example_device := class(creative_device):

    LoggerGeneral:log = log{Channel:=log_general}
    LoggerButtons:log = log{Channel:=log_buttons, 
                            DefaultLevel := log_level.Warning}

    var BtnWarningCount: int = 0
    var BtnErrorCount: int = 0

    @editable
    ButtonWarning : button_device = button_device{}

    @editable
    ButtonError : button_device = button_device{}

    OnBegin<override>()<suspends>:void=
        ButtonWarning.InteractedWithEvent.Subscribe(ButtonWarningPressed)
        ButtonError.InteractedWithEvent.Subscribe(ButtonErrorPressed)
        LoggerGeneral.Print("Experience started.")

    ButtonWarningPressed(Agent:agent):void=
        set BtnWarningCount += 1
        LoggerButtons.Print("ButtonWarning was pressed {BtnWarningCount} times")

    ButtonErrorPressed(Agent:agent):void=
        set BtnErrorCount += 1
        LoggerButtons.Print("ButtonError was pressed {BtnErrorCount} times", 
                            ?Level := log_level.Error)
        LoggerButtons.PrintCallStack()

The log_example_device contains two button_device instances that are used to log messages when pressed. One button is used for Warning level messages, and the other for Error level messages.

The OnBegin function subscribes the functions to be called on the buttons when they are pressed, and then logs a message using LoggerGeneral.

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

Access the Content Drawer and add the log_example_device to the level. Then add two Button Devices to the level. 



Select the log_example_device at the level. In the Details tab, Select the references to the buttons in the level. 


Save the level and click the Launch Session button to load the level in Fortnite. Press the buttons a few times. Then switch to UEFN and check the messages logged in the Output Log.



UEFN Verse: Logging e Log channel

Mensagens escritas no log podem ajudar a identificar problemas no seu código Verse. Estas mensagens podem ser visualizadas na aba de log dentro do jogo e na janela Output Log do UEFN.

Para escrever logs em Verse, você precisa usar duas classes: log e log_channel.

O log_channel é usado apenas para identificar a origem da mensagem. Seu nome é adicionado ao início da mensagem.

É necessário criar uma subclasse de log_channel no escopo de módulo, ou seja, fora de classes ou funções. O código abaixo mostra um exemplo de log_channel:

log_general := class(log_channel){}

O próximo passo é criar uma instância da classe log dentro de uma classe ou função, informando o log_channel que será utilizado:

LoggerGeneral:log = log{Channel:=log_general}

Existem 5 níveis de log que podem ser usados para categorizar a mensagem: Debug, Verbose, Normal, Warning e Error.

Logs com níveis Debug e Verbose aparecem apenas na aba de log dentro do jogo. Eles não aparecem no Output Log do UEFN.

Logs com níveis Warning e Error são exibidos em cores diferentes para chamar mais atenção.

É possível definir um nível padrão para um log no momento de sua criação: 

LoggerGeneral:log = log{Channel:=log_general, DefaultLevel:=log_level.Warning}

Para escrever no log, use a função Print da classe log:

LoggerGeneral.Print("Experience started")

Você pode passar como parâmetro o nível de log da mensagem:

LoggerGeneral.Print("Data not found", ?Level := log_level.Error)

Outra informação útil na análise de problemas é o Call Stack (pilha de chamadas) que mostra as funções chamadas até chegar ao ponto atual do código. Use a função PrintCallStack da classe log para registrar o Call Stack. 

LoggerGeneral.PrintCallStack()

Para ilustrar o uso de logs, vamos criar um dispositivo que utiliza dois logs. Um deles será usado para mensagens gerais do sistema e o outro log será para registrar mensagens quando os botões forem pressionados pelo jogador. Serão usados diferentes níveis de log.

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

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

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

log_general := class(log_channel){}
log_buttons := class(log_channel){}

log_example_device := class(creative_device):

    LoggerGeneral:log = log{Channel:=log_general}
    LoggerButtons:log = log{Channel:=log_buttons, 
                            DefaultLevel := log_level.Warning}

    var BtnWarningCount: int = 0
    var BtnErrorCount: int = 0

    @editable
    ButtonWarning : button_device = button_device{}

    @editable
    ButtonError : button_device = button_device{}

    OnBegin<override>()<suspends>:void=
        ButtonWarning.InteractedWithEvent.Subscribe(ButtonWarningPressed)
        ButtonError.InteractedWithEvent.Subscribe(ButtonErrorPressed)
        LoggerGeneral.Print("Experience started.")

    ButtonWarningPressed(Agent:agent):void=
        set BtnWarningCount += 1
        LoggerButtons.Print("ButtonWarning was pressed {BtnWarningCount} times")

    ButtonErrorPressed(Agent:agent):void=
        set BtnErrorCount += 1
        LoggerButtons.Print("ButtonError was pressed {BtnErrorCount} times", 
                            ?Level := log_level.Error)
        LoggerButtons.PrintCallStack()

O dispositivo log_example_device possui dois button_device que serão usados para registrar mensagens no log quando forem pressionados. Um botão será usado para mensagens com o nível Warning e o outro para mensagens com o nível Error.

A função OnBegin registra, nos botões, as funções que serão chamadas quando eles forem pressionados e, em seguida, escreve uma mensagem no log usando o LoggerGeneral.

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

Acesse o Content Drawer e adicione o dispositivo log_example_device ao nível. Em seguida, adicione dois Button Devices ao nível. 



Selecione o log_example_device no nível. Na aba Details, selecione as referências aos botões que estão no nível. 


Salve o nível e clique no botão Launch Session para carregar o nível no Fortnite. Pressione os botões algumas vezes. Em seguida, alterne para o UEFN e verifique no Output Log as mensagens registradas.  



quinta-feira, 19 de março de 2026

UEFN Verse: Extension Methods

Methods are functions that belong to a class, just as fields or attributes represent class data, such as variables and constants. This terminology comes from Object-Oriented Programming.

The Verse language allows the creation of extension methods, which are functions that can be added to existing classes without the need for inheritance.

This can be useful when you need to add functionality to classes that cannot be extended, such as player, agent, and team in UEFN.

In addition to classes, extension methods can be used with any type in Verse. The example below adds a function to the int type that calculates the power of a number.

(Base:int).MyPowFunction(Exponent:int):int=
    if (Exponent < 0):
        return 0
    var PowResult: int = 1
    for (Ind := 1..Exponent):
        set PowResult *= Base
    PowResult

Inside the parentheses is a constant of the type being extended. This constant is used in the function body as if it were a parameter.

The following code shows how to use the function:

IntValue := 2
Result := IntValue.MyPowFunction(4)


We will use extension methods to add functionality to the player class in UEFN. To do this, a new class and a map will be used to associate additional fields with a player instance.

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

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

Copy the Verse code below into the extension_device file:

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

player_fields := class:
    var Score : int = 0
    var CoinsCollected : int = 0
    var GameLevel : int = 1
    var CoinsPerLevel : int = 3    

extension_device := class(creative_device):

    @editable
    ItemSpawnerArray : []item_spawner_device = array{}

    var PlayerFieldsMap<public> : [player]player_fields  = map{}

    OnBegin<override>()<suspends>:void =
        for(ItemSpawner : ItemSpawnerArray):
            ItemSpawner.ItemPickedUpEvent.Subscribe(HandleCoinCollected)

    HandleCoinCollected(Agent:agent):void=
        if ( Player := player[Agent], Player.CollectCoin[] ) {}

    (Player:player).GetPlayerFields()<decides><transacts>:player_fields=
        if(PlayerFields := PlayerFieldsMap[Player]):
            PlayerFields
        else:
            NewPlayerFields := player_fields{}
            set PlayerFieldsMap[Player] = NewPlayerFields
            NewPlayerFields

    (Player:player).CollectCoin()<decides><transacts>:void=
        PlayerFields := Player.GetPlayerFields[]
        set PlayerFields.CoinsCollected += 1
        set PlayerFields.Score += PlayerFields.GameLevel * 100
        if ( Mod[PlayerFields.CoinsCollected, PlayerFields.CoinsPerLevel] = 0 ):
            set PlayerFields.GameLevel += 1
        Print("Score:{PlayerFields.Score} | GameLevel:{PlayerFields.GameLevel}")

The player_fields class contains the new fields that will be associated with a player instance through the PlayerFieldsMap map.

The extension_device contains an array of item_spawner_device used to store references to the Item Spawners in the level. The OnBegin function registers HandleCoinCollected on each instance in the item_spawner_device array so it is executed when the player collects a coin.

The HandleCoinCollected function receives the agent that collected the coin as a parameter. It is cast to player, and then the CollectCoin extension method created for the player class is called. The if expression is used only as a failure context.

GetPlayerFields is an extension method created for the player class. It returns the player_fields instance associated with the player. If it does not exist yet, a new player_fields instance is created, stored in the map, and returned by the method.

CollectCoin is another extension method for the player class. It retrieves the player_fields instance to update its values. In this example, GameLevel increases every three coins collected, and the score awarded for each coin depends on it.

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

Access the Content Drawer and add the constructor_device to the level. Add an Item Spawner Device to the level and, in the Details tab, configure it as shown in the image so that a coin is generated every 3 seconds.


Make copies of the Item Spawner Device by holding Alt and dragging one of the axis arrows on the selected device. In my example, there are four Item Spawners.


Select the extension_device at the level. In the Details tab, add elements to the array and select the Item Spawner Device references for each element.


Save the level and click the Launch Session button to load the level in Fortnite. When a coin is collected, a message is displayed showing the player's current Score and GameLevel.