segunda-feira, 29 de junho de 2026

UEFN Verse: NPC Spawner device

NPC stands for Non-Playable Character. NPCs are characters controlled by the game, including guards, villagers, wild animals, and many other types of characters.

UEFN includes specialized spawner devices for spawning standard characters, such as guards (Guard Spawner) and creatures (Wildlife Spawner). These devices provide many configuration options that are worth exploring, as they can handle a wide variety of use cases.

To customize NPC appearance and behavior, use the NPC Spawner device. It works together with two types of assets that enable the same appearance and behavior to be reused across multiple NPC Spawners:

  • NPC Character Definition: Defines the NPC's type, appearance, modifiers, and behavior.
  • NPC Behavior Script: Verse script that defines the NPC's behavior.


In the following articles, we will explore these two types of assets in greater detail.

The image below shows some of the properties of an NPC Spawner:


The Spawn Count field specifies how many NPCs spawned by this spawner can be active at the same time.

The NPC Character Definition must be selected. The NPC Behavior Script override field is optional because every NPC Character Definition is already associated with a Behavior Script. However, you can override it by assigning a different script in the NPC Spawner.

The Spawn On Timer property determines whether NPCs are spawned automatically by the NPC Spawner. When set to false, NPCs can only be spawned through Verse code.

The following properties expose the functions and events available in the NPC Spawner:


We will create a device that demonstrates how to control an NPC Spawner using Verse code. The Spawn Count property will be set to 1, ensuring that only one NPC is active at any given time.

The device runs a loop that spawns an NPC and waits for it to be eliminated. Each time an NPC is eliminated, the elimination counter is updated and displayed on the screen. The loop then starts again.

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

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

Copy the Verse code below into the npc_spawner_manager file:

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

npc_spawner_manager := class(creative_device):

    @editable
    NpcSpawner : npc_spawner_device = npc_spawner_device{}

    var EliminatedCount : int = 0

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

        loop:
            NpcSpawner.Spawn()
            NpcSpawner.EliminatedEvent.Await()

            set EliminatedCount += 1
            Print("Guards eliminated: {EliminatedCount}")
            Sleep(0.1)

The npc_spawner_manager device holds a reference to an npc_spawner_device. This reference is used to call the Spawn() function and wait for the EliminatedEvent to be triggered.

In this example, the npc_spawner_device is configured to allow only one active NPC at a time. Therefore, a Sleep(0.1) call is required to give the device time to update its internal state. Without this delay, Spawn() would not create a new NPC because the previously eliminated NPC would still be considered active internally.

Note: An infinite loop must contain at least one call to a <suspends> function, such as Sleep() or Await(), to yield control back to the engine. Otherwise, the engine will terminate the loop and a runtime error will be generated.


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 npc_spawner_manager to the level.  We will need an NPC Spawner Device and an Item Spawner Device. The image below shows the elements that we will use in this example.



It will be necessary to create an NPC Character Definition to use with the NPC Spawner Device. We will create a very simple one. In the next article, we will take a closer look at the NPC Character Definition.

In the project folder in the Content Drawer, right-click on an empty space and select the Artificial Intelligence > NPC Character Definition option, as shown in the image.



Name it GuardRandomCharDef and double-click it to edit its properties. The NPC will be a Guard type and will use the default behavior. There is a list of modifiers used to define an NPC.

In the Team Modifier, change the Team Index to 2. This way, the NPCs will be on a different team from the player and will therefore attack them. In the Cosmetic Modifier, change the Character Look to Random Fortnite Character to add variety to the generated NPCs.


Select the NPC Spawner Device in the level. In the Details panel, change the NPC Character Definition to the new GuardRandomCharDef. Uncheck the Spawn On Timer property so that NPCs are spawned only through Verse code.


Select the npc_spawner_manager in the level. in the Details panel, select the reference to the NPC Spawner Device.  


We will provide a weapon for the player to defend against the NPCs. Select the Item Spawner in the level and add an element to the Item List. Choose some type of rifle.

Set Time Before First Spawn to 0 so that the weapon is available immediately at the start of the match.


We will provide infinite ammo for the player. In the Outliner panel, select Island Settings. In the Details panel, search for Infinite. Check the Infinite Magazine Ammo property. This property is located in the Inventory category.



Save the level and click the Launch Session button to load it in Fortnite. Eliminate the NPC so that a new NPC with a different appearance is generated.


UEFN Verse: Dispositivo NPC Spawner

NPC significa Non-Playable Character (personagem não jogável). São personagens controlados pelo jogo, como guardas, moradores de uma vila, animais selvagens, entre outros.

O UEFN possui dispositivos spawner especializados na criação de personagens padrões, como guardas (Guard Spawner) e criaturas (Wildlife Spawner). Esses dispositivos oferecem diversas opções de configuração que recomendo experimentar, pois podem ser suficientes para muitos casos.

Para personalizar a aparência e comportamento dos NPCs, podemos usar o dispositivo NPC Spawner. Este dispositivo é usado em conjunto com dois tipos de assets, que permitem reutilizar a aparência e o comportamento em vários NPC Spawners:

  • NPC Character Definition: Usado para definir o tipo, a aparência,  os modificadores e o comportamento do NPC.
  • NPC Behavior Script: Script em Verse que define o comportamento do NPC.


Nos próximos artigos, vamos explorar esses dois tipos de assets com mais detalhes.

A imagem abaixo mostra algumas das propriedades de um NPC Spawner:


O campo Spawn Count indica quantos NPCs gerados por esse spawner podem permanecer ativos ao mesmo tempo.

NPC Character Definition deve ser selecionado. O campo NPC Behavior Script override é opcional porque um NPC Charater Definition já está associado a um Behavior Script. No entanto, esse comportamento pode ser substituído por  script nesse campo do NPC Spawner.

O campo Spawn On Timer indica se o os NPCs são gerados automaticamente pelo NPC Spawner. Se esse campo estiver definido como false, os NPCs serão gerados apenas por código verse.

Nas propriedades, podemos ver as funções e os eventos disponíveis no NPC Spawner:


Vamos criar um dispositivo para demonstrar como controlar um NPC Spawner usando código Verse. O Spawn Count do NPC Spawner será definido como 1, para que apenas um NPC permaneça ativo por vez. 

O dispositivo mantém um loop que gera um NPC e aguarda até que ele seja eliminado. Um contador de NPCs eliminados é atualizado e exibido na tela. Em seguida, o loop se repete. 

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

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

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

npc_spawner_manager := class(creative_device):

    @editable
    NpcSpawner : npc_spawner_device = npc_spawner_device{}

    var EliminatedCount : int = 0

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

        loop:
            NpcSpawner.Spawn()
            NpcSpawner.EliminatedEvent.Await()

            set EliminatedCount += 1
            Print("Guards eliminated: {EliminatedCount}")
            Sleep(0.1)

O dispositivo npc_spawner_manager possui uma referência a um npc_spawner_device, que é usada para chamar a função Spawn() e aguardar o acionamento do evento EliminatedEvent.

Neste exemplo, o npc_spawner_device será configurado para manter apenas um NPC ativo por vez. Por isso, foi usada a função Sleep() com uma pausa de 0,1 segundo para dar tempo ao npc_spawner_device de atualizar seu estado interno. Sem a chamada a Sleep(), a função Spawn() não geraria um novo NPC , pois o NPC eliminado ainda estaria registrado internamente como ativo.

Nota: Um loop infinito precisa conter pelo menos uma chamada a uma função <suspends>, como Sleep() ou Await(), para devolver o controle à engine.  Caso contrário, a engine encerrará o loop e um erro de runtime será gerado.


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 novo dispositivo npc_spawner_manager ao nível. Vamos precisar de um NPC Spawner Device e um Item Spawner Device. A imagem abaixo mostra os elementos que vamos usar neste exemplo.



Será necessário criar um NPC Character Definition para usar no NPC Spawner Device. Vamos criar um bem simples. No próximo artigo veremos o NPC Character Definition com mais detalhes. 

Na pasta do projeto no Content Drawer, clique com o botão direito do mouse em um espaço vazio e selecione a opção Artificial Intelligence > NPC Character Definition como mostra a imagem.



Coloque o nome de GuardRandomCharDef e dê dois cliques para editar as propriedades. O NPC será do tipo Guard e usará o comportamento padrão. Existe uma lista de modificadores usados para definir um NPC. 

No Team Modifier, altere o Team Index para 2. Dessa forma os NPCs ficarão em um time diferente do jogador e por isso vão atacá-lo. No Cosmetic Modifier, altere o Character Look para Random Fortnite Character para termos variedade nos NPCs gerados.


Selecione o NPC Spawner Device no nível. Na aba Details, mantenha Spawn Count em 1 e mude o NPC Character Definition para o novo GuardRandomCharDef. Desmarque a propriedade Spawn On Timer para que os NPCs sejam gerados somente por código Verse.


Selecione o npc_spawner_manager no nível. Na aba Details, selecione a referência ao NPC Spawner Device.  


Vamos fornecer uma arma para o jogador se defender dos NPCs. Selecione o Item Spawner no nível e adicione um elemento na Item List. Escolha algum tipo de rifle.  

Coloque o valor 0 em Time Before First Spawn para que arma esteja disponivel imediatamente no início da partida.


Vamos fornecer munição infinita para o jogador. Na aba Outliner, selecione o Island Settings. Na aba Details, pesquise por Infinite. Marque a propriedade Infinite Magazine Ammo. Esta propriedade fica na categoria Inventory.



Salve o nível e clique no botão Launch Session para carregá-lo no Fortnite. Elimine o NPC para que seja gerado um novo NPC com aparência diferente.


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.