Open1

[UEFN][Verse]イベント処理の実装

イワケンイワケン

土屋さんの記事を参考
https://zenn.dev/t_tutiya/articles/adf6cf84eaded0


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

# See https://dev.epicgames.com/documentation/en-us/uefn/create-your-own-device-in-verse for how to create a verse device.

# A Verse-authored creative device that can be placed in a level
event_device := class(creative_device):

    @editable
    MyButton : button_device = button_device{}
    @editable
    Switches : []switch_device = array{switch_device{}}

    var SwitchEvents: []custom_event = array{}

    Event<public>:event(agent) = event(agent){}

    # Runs when the device is started in a running game
    OnBegin<override>()<suspends>:void=
        # for(Index -> Switch: Switches):
        #     spawn{AwaitSwitchTurnedOn(Switch,Index)}
        MyButton.InteractedWithEvent.Subscribe(HandleButtonInteraction)

        for:
            Switch:Switches
        do:
            EventObj : custom_event = custom_event{Switch := Switch}
            set SwitchEvents += array{EventObj}
            spawn{Subscribe(EventObj)}
    AwaitSwitchTurnedOn<private>(Switch:switch_device, Index:int)<suspends>:void=
        loop:
            Switch.TurnedOnEvent.Await()
            Print("Switch[{Index}] turned on")

    

    Subscribe(CustomEvent:custom_event)<suspends>:void=
        Agent := CustomEvent.Event.Await()
        CustomEvent.Switch.ToggleState(Agent)
        spawn{Subscribe(CustomEvent)}

    HandleButtonInteraction(Agent : agent) : void=
        for:
            SwitchEvent : SwitchEvents
        do:
            SwitchEvent.Emit(Agent)

custom_event := class():
    Switch : switch_device

    Event<public>:event(agent) = event(agent){}

    Emit<public>(Agent:agent):void=
        Event.Signal(Agent)