Listening-for-events

From FiveM Wikipedia

Прослушивание событий

Чтобы использовать существующие события в ресурсах, необходимо их прослушивать. То же самое относится и к клиентским/серверным сценариям.

В Lua/JS source переменная (global) будет содержать идентификатор игрока, который вызвал событие. Скорее всего, его следует сохранить в локальной переменной, если вы собираетесь использовать его после возврата события.

В C# используется атрибут, как показано в примере ниже.[FromSource]

Пример

Lua

AddEventHandler("eventName", function(eventParam1, eventParam2)
    -- Code here will be executed once the event is triggered.
end)

C #

// Usually in the constructor of a class that inherits BaseScript, but can be done anywhere in a BaseScript.
EventHandlers["eventName"] += new Action<string, bool>(TargetFunction);

// Create a function to handle the event somewhere else in your code, or use a lambda.
private void TargetFunction(string param1, bool param2)
{
    // Code that gets executed once the event is triggered goes here.
}


Использование исходного кода (на сервере) работает следующим образом:

// constructor code
EventHandlers["netEventName"] += new Action<Player, string, bool>(TargetFunction);


// Create a function to handle the event somewhere else in your code, or use a lambda.
private void TargetFunction([FromSource] Player source, string param1, bool param2)
{
    // Code that gets executed once the event is triggered goes here.
    // The variable 'source' contains a reference to the player that triggered the event.
}

.JS

on('eventName', (eventParam1, eventParam2) => {
    // Code that gets executed once the event is triggered goes here.
});

Примечание при использовании Lua/JS

Если вы хотите, чтобы ваши события были доступны «по сети» (то есть инициируют клиентское событие из серверного сценария или инициируют событие сервера из клиентского сценария), вам необходимо сначала зарегистрировать событие.

Чтобы зарегистрировать событие как сетевое, поместите его в клиент-серверный сценарий:

Lua

RegisterNetEvent("eventName")

-- The event handler function follows after registering the event first.
AddEventHandler("eventName", function(eventParam1, eventParam2)
    -- Code here will be executed once the event is triggered.
end)

.JS

Примечание: события onNet могут выполняться как локально, так и удаленно

onNet('eventName', (eventParam1, eventParam2) => {
    // Code here will be executed once the event is triggered.
})

Вам нужно только регистрировать события при использовании Lua или JS - C# не требует, чтобы вы делали это вручную, хотя вы можете защитить события вашего сервера с помощью собственного кода.


Работа с событиями