Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

fivem lua how could I trigger an event when a player joins a server and when the player…

  1. User

    fivem lua

    how could I trigger an event when a player joins a server and when the player leaves the server

  2. Assistant

    You can use server-sided events to trigger a function when a player joins or leaves the server. Here is an example using the "playerConnecting" and "playerDropped" events in a FiveM Lua script:

    -- Triggered when a player joins the server
    AddEventHandler('playerConnecting', function(playerName, setKickReason, deferrals)
        -- You can replace the print statement with your own code
        print(playerName .. ' is joining the server.')
    end)
    
    -- Triggered when a player leaves the server
    AddEventHandler('playerDropped', function(reason)
        -- Get the player's name
    	local playerName = GetPlayerName(source)
    
    	-- You can replace the print statement with your own code
        print(playerName .. ' left the server. Reason: ' .. reason)
    end)
    

    Put this code in a new ".lua" file inside your resource folder and add it to the "_resource.lua" file to be executed.

    In this example, the server console will print the player's name and the reason they left when a player joins or leaves the server. You can replace the "print" statements with your own code, such as triggering other events or sending notifications.

  3. User

    how could I get the players server id when they join

  4. Assistant

    You can get the player's server ID in the playerConnecting event by using the source variable. Here's an example:

    -- Triggered when a player joins the server
    AddEventHandler('playerConnecting', function(playerName, setKickReason, deferrals)
        -- Get the player's server ID
        local playerServerId = source
    
        -- You can replace the print statements with your own code
        print(playerName .. ' is joining the server with Server ID: ' .. playerServerId)
    end)
    

    In this example, the server console will print the player's name and server ID when they join. You can use the playerServerId variable for other purposes, such as storing it or passing it to another function.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.