# ๐Ÿ“‘ Misc Guides Source: https://rsg.mintlify.app/MiscGuides Extra guides and tools are listed here ## Getting the Players **To get a list of players on the server we must use either a native that is like this** ```lua theme={null} for _, player in ipairs(GetActivePlayers()) do local ped = GetPlayerPed(player) -- do stuff end ``` **Using the RSG function you can do it like this** ```lua theme={null} for _, player in pairs(RSGCore.Functions.GetPlayers()) do local ped = GetPlayerPed(player) -- do stuff end ``` ## Database Connection txAdmin does this automatically already but if needed then in your server.cfg put this and fill it in with the correct information. For the database wrapper [oxmysql](https://github.com/overextended/oxmysql) ### Installation[โ€‹](https://overextended.github.io/docs/oxmysql/#installation) * Download the [latest build](https://github.com/overextended/oxmysql/releases/latest) of oxmysql (not the source code). * Extract the contents of the archive to your resources folder. * Start the resource near the top of your resources in your `server.cfg`. * If you have a lot of streamed assets, load them first to prevent timing out the connection. ### [](https://docs.qbcore.org/qbcore-documentation/guides/miscellaneous-guides#configuration)Configuration[โ€‹](https://overextended.github.io/docs/oxmysql/#configuration) You can change the configuration settings by using convars inside your `server.cfg`. Reference the following for an idea of how to set your connection options. You must include one of the following lines, adjusted for your connection and database settings. ``` set mysql_slow_query_warning 150set mysql_debug true ``` Certain special characters are reserved or blocked and may cause issues when used in your password. For more optional settings (such as multiple statements) you can reference [pool.d.ts](https://github.com/sidorares/node-mysql2/blob/master/typings/mysql/lib/Pool.d.ts#L10) and [connection.d.ts](https://github.com/sidorares/node-mysql2/blob/master/typings/mysql/lib/Connection.d.ts#L8). You can also add the following convars if you require extra information when testing queries. ``` set mysql_slow_query_warning 150set mysql_debug true ``` ## Server.cfg Setting up your server.cfg is really simple and is already completed upon a successful txAdmin recipe install! You can also find additional information on server configuration files [**here**](https://docs.fivem.net/docs/server-manual/setting-up-a-server/)**.** In case of a manual install then here's a template to use ``` ## server main settings {{serverEndpoints}} sv_maxclients {{maxClients}} set gamename rdr3 set sv_enforceGameBuild 1491 # https://docs.fivem.net/docs/server-manual/server-commands/#sv_purelevel-level #sets sv_pureLevel 1 #sets sv_pureLevel 2 # locale config setr rsg_locale "en" setr ox:locale en ## key license settings sv_licenseKey "{{svLicense}}" set steam_webApiKey "none" ## database settings set mysql_connection_string "{{dbConnectionString}}" set mysql_slow_query_warning 300 ## server settings sv_hostname "{{serverName}} built with {{recipeName}} by {{recipeAuthor}}!" sets sv_projectName "[{{recipeName}}] {{serverName}}" sets sv_projectDesc "{{recipeDescription}}" sets locale "en-US" load_server_icon myLogo.png sets Framework "RSG" sets Framework Discord "https://discord.gg/eW3ADkf4Af" sets banner_detail "link" sets banner_connecting "link" sets Discord "link" sets Developer "link" sets tags "rsg,roleplay" sv_endpointprivacy true set txAdmin-menuPtfxDisable true # Disable TXAdmin NoClip Particle Effect set sv_experimentalNetGameEventHandler false # https://v6.mantine.dev/theming/colors/#default-colors setr ox:primaryColor red setr ox:primaryShade 8 # use target setr UseTarget false # default resources ensure mapmanager ensure spawnmanager ensure sessionmanager-rdr3 #ensure basic-gamemode #ensure hardcap # database and library ensure oxmysql ensure ox_lib # resources ensure rsg-core ensure rsg-multicharacter ensure rsg-spawn ensure rsg-menubase ensure ox_target ensure ip-chat ensure [standalone] ensure [framework] ensure [mapmods] ## weathersync permissions exec resources/[standalone]/weathersync/permissions.cfg ## Permissions ## add_ace group.admin command allow # allow all commands add_principal identifier.license:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx rsgcore.god # << your rockstar licence add_principal identifier.license:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx group.admin # << your rockstar licence # Resources add_ace resource.rsg-core command allow # Allow rsg-core to execute commands # Gods add_ace rsgcore.god command allow # Allow all commands # Inheritance add_principal rsgcore.god group.admin # Allow gods access to the main admin group used to get all default permissions add_principal rsgcore.god rsgcore.admin # Allow gods access to admin commands add_principal rsgcore.admin rsgcore.mod # Allow admins access to mod commands ``` ## GitHub Pull Request **Github:** [RSG RedM Framework](https://github.com/Rexshack-RedM) * Visit the resource you would like to propose changes on * Navigate to the exact file within that resource * Click on the pencil icon and you will be able to make edits to the code * Once you are satisfied with your edits, scroll down to the box labeled "Propose Changes" * Write a title and short description of what the changes are * Once that's filled out, press the green "Propose Changes" button * You will see a screen showing your edits compared to the existing code * If you are satisfied with the edits shown, press the green "Create Pull Request" button * Fill in the title and description if necessary * Click on the green "Create Pull Request" button and it's finished! If you have email notifications enabled, you will get any updates on the pull request by email # ๐ŸŽฎ Client Events Source: https://rsg.mintlify.app/api-reference/endpoint/clienteventreference Complete guide to RSG Core client-side events and event handlers ## Introduction Client events are essential for handling player-specific actions, UI updates, and local game state changes in RSG Framework. They run on each player's machine and allow for responsive, individualized gameplay experiences. Client events run locally on each player's machine and can be triggered by the server using `TriggerClientEvent` or by other client-side code using `TriggerEvent`. *** ## How It Works ### Event Flow ``` Server Script โ†’ TriggerClientEvent('eventName', source, args) โ†’ Client Listens โ†’ Client Processes ``` Or locally: ``` Client Script โ†’ TriggerEvent('eventName', args) โ†’ Same Client Listens โ†’ Client Processes ``` ### Registering Events Client events are registered using `RegisterNetEvent`: ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('eventName', function(arg1, arg2) -- Process event locally print('Received:', arg1, arg2) end) ``` Client events are **not synchronized** between players. Each player's client runs independently! *** ## Core Lifecycle Events ### RSGCore:Client:OnPlayerLoaded Triggered when a player successfully loads into the server after character selection. This is the most important event for initializing player-specific client-side features. ```lua theme={null} -- CLIENT SIDE local RSGCore = exports['rsg-core']:GetCoreObject() RegisterNetEvent('RSGCore:Client:OnPlayerLoaded', function() local PlayerData = RSGCore.Functions.GetPlayerData() print('Player loaded:', PlayerData.charinfo.firstname) -- Initialize player-specific features -- Set up HUD -- Load player blips -- Start player threads end) ``` **Use Cases:** * Initialize HUD elements * Start player status monitors * Load player-specific blips/markers * Set up keybinds * Initialize job-specific UI * Restore player settings **Complete Example:** ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Client:OnPlayerLoaded', function() local PlayerData = RSGCore.Functions.GetPlayerData() -- Start HUD TriggerEvent('hud:client:LoadHud', PlayerData) -- Start status update thread CreateThread(function() while true do -- Update hunger/thirst display Wait(30000) -- Every 30 seconds end end) -- Show welcome message lib.notify({ title = 'Welcome Back!', description = 'Hello, ' .. PlayerData.charinfo.firstname, type = 'success', duration = 5000 }) -- Job-specific initialization if PlayerData.job.name == 'police' then TriggerEvent('police:client:initPoliceJob') end end) ``` ### RSGCore:Client:OnPlayerUnload Triggered when a player logs out or returns to character selection. Use this to clean up client-side data and stop threads. ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Client:OnPlayerUnload', function() print('Player unloading...') -- Clean up HUD TriggerEvent('hud:client:UnloadHud') -- Stop custom threads -- Clear temporary blips -- Reset UI elements -- Save client settings end) ``` **Use Cases:** * Stop running threads * Clear temporary blips/markers * Reset UI to default state * Save client-side settings * Clean up job-specific features **Complete Example:** ```lua theme={null} -- CLIENT SIDE local activeThreads = {} local playerBlips = {} RegisterNetEvent('RSGCore:Client:OnPlayerUnload', function() -- Stop all active threads for _, thread in pairs(activeThreads) do thread.active = false end activeThreads = {} -- Remove all player blips for _, blip in pairs(playerBlips) do if DoesBlipExist(blip) then RemoveBlip(blip) end end playerBlips = {} -- Clear UI SendNUIMessage({ action = 'hideAll' }) print('Player unloaded and cleaned up') end) ``` *** ## Player Data Events ### RSGCore:Player:SetPlayerData Triggered whenever player data changes (job update, money change, metadata update, etc.). Essential for keeping UI synchronized with server data. ```lua theme={null} -- CLIENT SIDE local RSGCore = exports['rsg-core']:GetCoreObject() RegisterNetEvent('RSGCore:Player:SetPlayerData', function(newData) -- Update local PlayerData RSGCore.PlayerData = newData -- Update HUD with new data TriggerEvent('hud:client:UpdatePlayerData', newData) print('Player data updated') end) ``` **Use Cases:** * Update HUD when money changes * Refresh job display when job updates * Update status bars when metadata changes * Sync inventory UI * Update player name displays **Complete Example with Specific Updates:** ```lua theme={null} -- CLIENT SIDE local RSGCore = exports['rsg-core']:GetCoreObject() local lastMoney = {} local lastJob = nil RegisterNetEvent('RSGCore:Player:SetPlayerData', function(newData) local oldData = RSGCore.PlayerData RSGCore.PlayerData = newData -- Check for money changes if oldData.money then for moneyType, amount in pairs(newData.money) do if lastMoney[moneyType] and lastMoney[moneyType] ~= amount then local difference = amount - lastMoney[moneyType] if difference > 0 then lib.notify({ description = '+$' .. difference .. ' ' .. moneyType, type = 'success' }) end end lastMoney[moneyType] = amount end end -- Check for job changes if newData.job and newData.job.name ~= lastJob then lib.notify({ title = 'Job Updated', description = 'You are now: ' .. newData.job.label, type = 'info' }) lastJob = newData.job.name -- Trigger job-specific initialization TriggerEvent('job:client:onJobChange', newData.job) end -- Update HUD SendNUIMessage({ action = 'updatePlayerData', data = newData }) end) ``` *** ## Job & Duty Events ### RSGCore:Client:OnJobUpdate Triggered when a player's job changes. ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Client:OnJobUpdate', function(job) print('Job updated to:', job.label) print('Grade:', job.grade.name) print('On Duty:', job.onduty) -- Update job-specific UI SendNUIMessage({ action = 'updateJob', job = job }) -- Job-specific logic if job.name == 'police' then TriggerEvent('police:client:setupPoliceJob') elseif job.name == 'doctor' then TriggerEvent('doctor:client:setupDoctorJob') end end) ``` **Complete Example:** ```lua theme={null} -- CLIENT SIDE local currentJobBlips = {} RegisterNetEvent('RSGCore:Client:OnJobUpdate', function(job) -- Clean up old job blips for _, blip in pairs(currentJobBlips) do if DoesBlipExist(blip) then RemoveBlip(blip) end end currentJobBlips = {} -- Add new job blips if job.name == 'police' then -- Add police station blip local blip = Citizen.InvokeNative(0x554D9D53F696D002, 1664425300, Config.PoliceStation.x, Config.PoliceStation.y, Config.PoliceStation.z) SetBlipSprite(blip, -1282792512, 1) currentJobBlips[#currentJobBlips + 1] = blip end lib.notify({ title = 'Job Changed', description = 'You are now a ' .. job.label, type = 'info' }) end) ``` ### RSGCore:Client:SetDuty Triggered when a player's duty status changes. ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Client:SetDuty', function(onDuty) print('Duty status:', onDuty and 'ON DUTY' or 'OFF DUTY') -- Update duty indicator SendNUIMessage({ action = 'setDuty', onDuty = onDuty }) -- Show/hide duty-specific features if onDuty then -- Enable job features else -- Disable job features end end) ``` *** ## Vehicle Events ### RSGCore:Command:SpawnVehicle Spawns a vehicle near the player. ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Command:SpawnVehicle', function(model) local ped = PlayerPedId() local coords = GetEntityCoords(ped) local heading = GetEntityHeading(ped) -- Load vehicle model local modelHash = GetHashKey(model) lib.requestModel(modelHash) -- Spawn vehicle local vehicle = CreateVehicle(modelHash, coords.x + 2, coords.y, coords.z, heading, true, false) -- Set player in vehicle SetPedIntoVehicle(ped, vehicle, -1) -- Clean up SetModelAsNoLongerNeeded(modelHash) lib.notify({ description = 'Vehicle spawned: ' .. model, type = 'success' }) end) ``` **Trigger from Server:** ```lua theme={null} -- SERVER SIDE RSGCore.Commands.Add('spawnveh', 'Spawn vehicle', {{name = 'model', help = 'Vehicle model'}}, true, function(source, args) TriggerClientEvent('RSGCore:Command:SpawnVehicle', source, args[1]) end, 'admin') ``` **Trigger from Client:** ```lua theme={null} -- CLIENT SIDE RegisterCommand('spawnveh', function(_, args) local model = args[1] if not model then lib.notify({description = 'Usage: /spawnveh [model]', type = 'error'}) return end TriggerEvent('RSGCore:Command:SpawnVehicle', model) end) ``` ### RSGCore:Command:DeleteVehicle Deletes the vehicle the player is in or near. ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Command:DeleteVehicle', function() local ped = PlayerPedId() local vehicle = GetVehiclePedIsIn(ped, false) -- If not in vehicle, get closest vehicle if vehicle == 0 then local coords = GetEntityCoords(ped) vehicle = GetClosestVehicle(coords.x, coords.y, coords.z, 5.0, 0, 70) end if vehicle ~= 0 then DeleteEntity(vehicle) lib.notify({ description = 'Vehicle deleted', type = 'success' }) else lib.notify({ description = 'No vehicle nearby', type = 'error' }) end end) ``` **Trigger from Command:** ```lua theme={null} -- CLIENT SIDE RegisterCommand('dv', function() TriggerEvent('RSGCore:Command:DeleteVehicle') end) ``` *** ## Item & Inventory Events ### RSGCore:Client:UseItem Triggered when a player uses an item. Often called by the server after validation. ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Client:UseItem', function(item) print('Using item:', item.name) print('Amount:', item.amount) print('Slot:', item.slot) -- Play animation local ped = PlayerPedId() lib.requestAnimDict('mech_inventory@eating') TaskPlayAnim(ped, 'mech_inventory@eating', 'eat', 8.0, 8.0, 3000, 0, 0, true, true, true) -- Wait for animation Wait(3000) -- Clean up ClearPedTasks(ped) RemoveAnimDict('mech_inventory@eating') end) ``` **Complete Example with Progress Bar:** ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Client:UseItem', function(item) if item.name == 'bread' then -- Show progress bar if lib.progressBar({ duration = 3000, label = 'Eating bread...', useWhileDead = false, canCancel = true, disable = { move = false, car = true, combat = true }, anim = { dict = 'mech_inventory@eating@multi_bite@wedge_sandwich', clip = 'eat_wedge_sandwich' } }) then -- Notify server item was consumed TriggerServerEvent('consumables:server:eatFood', item.slot) lib.notify({ description = 'You ate bread', type = 'success' }) else lib.notify({ description = 'Cancelled', type = 'error' }) end end end) ``` *** ## System Events ### RSGCore:Client:PvpHasToggled Triggered when PVP mode is enabled or disabled for the player. ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Client:PvpHasToggled', function(pvpEnabled) print('PVP mode:', pvpEnabled and 'ENABLED' or 'DISABLED') -- Update network mode SetCanAttackFriendly(PlayerPedId(), true, pvpEnabled) NetworkSetFriendlyFireOption(pvpEnabled) -- Notify player lib.notify({ description = pvpEnabled and 'PVP Enabled' or 'PVP Disabled', type = 'info' }) -- Update UI SendNUIMessage({ action = 'setPvp', enabled = pvpEnabled }) end) ``` ### RSGCore:Client:UpdateObject Used to refresh the RSGCore object when using shared exports. Important for hot-reloading. ```lua theme={null} -- CLIENT SIDE local RSGCore = exports['rsg-core']:GetCoreObject() RegisterNetEvent('RSGCore:Client:UpdateObject', function() RSGCore = exports['rsg-core']:GetCoreObject() print('Core object updated') end) ``` This event is automatically triggered when rsg-core restarts. Include it in your resources to support hot-reloading! *** ## Notification Events ### Common Notification Pattern ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('myresource:client:notify', function(message, type) lib.notify({ description = message, type = type or 'info' }) end) -- Trigger from server -- SERVER SIDE TriggerClientEvent('myresource:client:notify', source, 'Action completed!', 'success') ``` *** ## Best Practices ### 1. Always Get Fresh PlayerData ```lua theme={null} -- GOOD RegisterNetEvent('myEvent', function() local PlayerData = RSGCore.Functions.GetPlayerData() -- Use fresh data end) -- BAD (can be outdated) local PlayerData = RSGCore.Functions.GetPlayerData() RegisterNetEvent('myEvent', function() -- Using old PlayerData end) ``` ### 2. Clean Up on Player Unload ```lua theme={null} -- GOOD local myBlips = {} local myThreads = {} RegisterNetEvent('RSGCore:Client:OnPlayerUnload', function() -- Clean up blips for _, blip in pairs(myBlips) do if DoesBlipExist(blip) then RemoveBlip(blip) end end -- Stop threads for _, thread in pairs(myThreads) do thread.active = false end end) ``` ### 3. Use Progress Bars for Actions ```lua theme={null} -- GOOD if lib.progressBar({ duration = 5000, label = 'Mining...', useWhileDead = false, canCancel = true, disable = { move = true, car = true, combat = true } }) then -- Action completed TriggerServerEvent('mining:server:collectOre') else -- Action cancelled end ``` ### 4. Validate Before Processing ```lua theme={null} -- GOOD RegisterNetEvent('myEvent', function(data) if not data or type(data) ~= 'table' then print('Invalid data received') return end -- Process data end) ``` *** ## Common Patterns ### Pattern 1: Animation with Callback ```lua theme={null} RegisterNetEvent('animations:client:playAnim', function(dict, anim, duration) local ped = PlayerPedId() lib.requestAnimDict(dict) TaskPlayAnim(ped, dict, anim, 8.0, 8.0, duration or -1, 0, 0, true, true, true) if duration and duration > 0 then Wait(duration) ClearPedTasks(ped) end RemoveAnimDict(dict) end) ``` ### Pattern 2: Proximity Activation ```lua theme={null} CreateThread(function() local shopCoords = vector3(2633.0, -1220.0, 53.0) local inRange = false while true do local ped = PlayerPedId() local coords = GetEntityCoords(ped) local distance = #(coords - shopCoords) if distance < 2.0 and not inRange then inRange = true lib.showTextUI('[E] Open Shop') elseif distance >= 2.0 and inRange then inRange = false lib.hideTextUI() end if inRange and IsControlJustPressed(0, RSGCore.Shared.Keybinds['E']) then TriggerServerEvent('shop:server:openShop') end Wait(inRange and 0 or 1000) end end) ``` ### Pattern 3: Status Monitor ```lua theme={null} RegisterNetEvent('RSGCore:Client:OnPlayerLoaded', function() CreateThread(function() while true do local PlayerData = RSGCore.Functions.GetPlayerData() if PlayerData.metadata then -- Update HUD SendNUIMessage({ action = 'updateStatus', hunger = PlayerData.metadata.hunger, thirst = PlayerData.metadata.thirst }) end Wait(5000) -- Update every 5 seconds end end) end) ``` *** ## Troubleshooting ### Event Not Triggering Some events only work after `RSGCore:Client:OnPlayerLoaded` Event names are case-sensitive and must match exactly Press F8 to open client console and look for error messages ### PlayerData is Nil ```lua theme={null} -- Wait for player to load RegisterNetEvent('myEvent', function() local PlayerData = RSGCore.Functions.GetPlayerData() if not PlayerData or not PlayerData.citizenid then print('Player not loaded yet') return end -- Safe to use PlayerData end) ``` ### UI Not Updating ```lua theme={null} -- Make sure to listen to PlayerData updates RegisterNetEvent('RSGCore:Player:SetPlayerData', function(newData) -- Update UI SendNUIMessage({ action = 'update', data = newData }) end) ``` *** ## Summary | Event | Purpose | Triggered By | | ------------------------------- | -------------- | ------------- | | `RSGCore:Client:OnPlayerLoaded` | Player login | Server | | `RSGCore:Client:OnPlayerUnload` | Player logout | Server | | `RSGCore:Player:SetPlayerData` | Data update | Server | | `RSGCore:Client:OnJobUpdate` | Job change | Server | | `RSGCore:Client:SetDuty` | Duty toggle | Server | | `RSGCore:Command:SpawnVehicle` | Spawn vehicle | Server/Client | | `RSGCore:Command:DeleteVehicle` | Delete vehicle | Server/Client | | `RSGCore:Client:UseItem` | Use item | Server | | `RSGCore:Client:PvpHasToggled` | PVP toggle | Server | | `RSGCore:Client:UpdateObject` | Refresh core | Server | *** ## Next Steps * [Server Events](/api-reference/endpoint/servereventreference) - Server-side event reference * [Client Functions](/api-reference/endpoint/clientfunctionreference) - Client function reference * [Threads & Loops](/lua-reference/threads) - Learn about CreateThread *** Need more help? Join the [RSG Framework Discord](https://discord.gg/rsg-redm-framework-914413479157448744)! # ๐ŸŽฎClient Function Reference Source: https://rsg.mintlify.app/api-reference/endpoint/clientfunctionreference Learn about and how to use common core client functions!! ### RSGCore.Functions.GetPlayerData * Perhaps the most used function in the framework. This function returns the players data of the current source which, since its used client side, is automatically the client or player. It can be used with modifiers on the end starting with a "." (period) ```lua theme={null} function RSGCore.Functions.GetPlayerData(cb) if not cb then return RSGCore.PlayerData end cb(RSGCore.PlayerData) end -- Example local Player = RSGCore.Functions.GetPlayerData() print(RSGCore.Debug(Player)) OR local Player = RSGCore.Functions.GetPlayerData() local jobName = Player.job.name print(jobName) ``` ### RSGCore.Functions.GetCoords * This function operates very similarly to how the native GetEntityCoords does, but it returns the heading as well ```lua theme={null} ---@param entity number ---@return vector4 function RSGCore.Functions.GetCoords(entity) local coords = GetEntityCoords(entity, false) local heading = GetEntityHeading(entity) return vector4(coords.x, coords.y, coords.z, heading) end -- Example local coords = RSGCore.Functions.GetCoords(PlayerPedId()) print(coords) ``` ### RSGCore.Functions.HasItem * Returns whether a player has a certain item ```lua theme={null} function RSGCore.Functions.HasItem(items, amount) return exports['rsg-inventory']:HasItem(items, amount) end local hasItem = RSGCore.Functions.HasItem('my_cool_item', 1) print(hasItem) ``` ### RSGCore.Functions.TriggerCaback * Function used to cal from the client to the server anbd receive a value back ```lua theme={null} function RSGCore.Functions.TriggerCallback(name, cb, ...) RSGCore.ServerCallbacks[name] = cb TriggerServerEvent('RSGCore:Server:TriggerCallback', name, ...) end -- Example RSGCore.Functions.TriggerCallback('callbackName', function(result) print('I got this from the CreateCallBack --> '..result) end, 'my_parameter_name') ``` ### RSGCore.Functions.GetVehicles * Returns a vehice game pool (for backwards compatibility) - Not worth using ```lua theme={null} function RSGCore.Functions.GetVehicles() return GetGamePool('CVehicle') end -- Example local vehicles = RSGCore.Functions.GetVehicles() print(RSGCore.Debug(vehicles)) OR -- preferred method local vehicles = GetGamePool('CVehicle') print(RSGCore.Debug(vehicles)) ``` ### RSGCore.Function.GetCoreObject * Returns the core object of the game ```lua theme={null} exports('GetCoreObject', function() return RSGCore end) local RSGCore = exports['rsg-core']:GetCoreObject() OR -- call the core in a single file that loads before the others RSGCore = exports['rsg-core']:GetCoreObject() ``` ### RSGCore.Function.GetPlayers * Returns a table of all players in the game - not worth using ```lua theme={null} function RSGCore.Functions.GetPlayers() return GetActivePlayers() end -- Example local players = RSGCore.Functions.GetPlayers() print(RSGCore.Debug(players)) OR -- preferred method local players = GetActivePlayers() print(RSGCore.Debug(players)) ``` ### RSGCore.Function.GetPeds * Returns a model hash filtered ped game pool ```lua theme={null} function RSGCore.Functions.GetPeds(ignoreList) local pedPool = GetGamePool('CPed') local peds = {} local ignoreTable = {} ignoreList = ignoreList or {} for i = 1, #ignoreList do ignoreTable[ignoreList[i]] = true end for i = 1, #pedPool do if not ignoreTable[pedPool[i]] then peds[#peds + 1] = pedPool[i] end end return peds end -- Example local peds = RSGCore.Functions.GetPeds({`mp_m_freemode_01`}) print(RSGCore.Debug(peds)) ``` ### RSGCore.Function.GetClosestPed * Returns the closest ped to the player's position ```lua theme={null} function RSGCore.Functions.GetClosestPed(coords, ignoreList) local ped = PlayerPedId() if coords then coords = type(coords) == 'table' and vec3(coords.x, coords.y, coords.z) or coords else coords = GetEntityCoords(ped) end ignoreList = ignoreList or {} local peds = RSGCore.Functions.GetPeds(ignoreList) local closestDistance = -1 local closestPed = -1 for i = 1, #peds, 1 do local pedCoords = GetEntityCoords(peds[i]) local distance = #(pedCoords - coords) if closestDistance == -1 or closestDistance > distance then closestPed = peds[i] closestDistance = distance end end return closestPed, closestDistance end -- Example local coords = GetEntityCoords(PlayerPedId()) local closestPed, distance = RSGCore.Functions.GetClosestPed(coords) print(closestPed, distance) ``` ### RSGCore.Functions.GetClosestVehicle * Returns the closest vehicle to the player ```lua theme={null} function RSGCore.Functions.GetClosestVehicle(coords) local ped = PlayerPedId() local vehicles = GetGamePool('CVehicle') local closestDistance = -1 local closestVehicle = -1 if coords then coords = type(coords) == 'table' and vec3(coords.x, coords.y, coords.z) or coords else coords = GetEntityCoords(ped) end for i = 1, #vehicles, 1 do local vehicleCoords = GetEntityCoords(vehicles[i]) local distance = #(vehicleCoords - coords) if closestDistance == -1 or closestDistance > distance then closestVehicle = vehicles[i] closestDistance = distance end end return closestVehicle, closestDistance end -- Example local coords = GetEntityCoords(PlayerPedId()) local closestVehicle, distance = RSGCore.Functions.GetClosestVehicle(coords) print(closestVehicle, distance) ``` ### RSGCore.Functions.GetClosestObject * Returns the closest player to the client ```lua theme={null} function RSGCore.Functions.GetClosestObject(coords) local ped = PlayerPedId() local objects = GetGamePool('CObject') local closestDistance = -1 local closestObject = -1 if coords then coords = type(coords) == 'table' and vec3(coords.x, coords.y, coords.z) or coords else coords = GetEntityCoords(ped) end for i = 1, #objects, 1 do local objectCoords = GetEntityCoords(objects[i]) local distance = #(objectCoords - coords) if closestDistance == -1 or closestDistance > distance then closestObject = objects[i] closestDistance = distance end end return closestObject, closestDistance end -- Example local coords = GetEntityCoords(PlayerPedId()) local closestObject, distance = RSGCore.Functions.GetClosestObject(coords) print(closestObject, distance) ``` ### RSGCore.Functions.GetPlayersFromCoords * Returns a list of players within a certain radius from the given coordinates ```lua theme={null} function RSGCore.Functions.GetPlayersFromCoords(coords, distance) local players = GetActivePlayers() local ped = PlayerPedId() if coords then coords = type(coords) == 'table' and vec3(coords.x, coords.y, coords.z) or coords else coords = GetEntityCoords(ped) end distance = distance or 5 local closePlayers = {} for _, player in ipairs(players) do local targetCoords = GetEntityCoords(GetPlayerPed(player)) local targetdistance = #(targetCoords - coords) if targetdistance <= distance then closePlayers[#closePlayers + 1] = player end end return closePlayers end -- Example local coords = GetEntityCoords(PlayerPedId()) local radius = 5.0 local closestPlayers = RSGCore.Functions.GetPlayersFromCoords(coords, radius) print(RSGCore.Debug(closestPlayers)) ``` ### RSGCore.Functions.SpawnVehicle * Spawns a vehicle at the given coordinates with the given model and color ```lua theme={null} ---@param model string|number ---@param cb? fun(vehicle: number) ---@param coords? vector4 player position if not specified ---@param isnetworked? boolean defaults to true ---@param teleportInto boolean teleport player to driver seat if true function RSGCore.Functions.SpawnVehicle(model, cb, coords, isnetworked, teleportInto) local playerCoords = GetEntityCoords(cache.ped) local combinedCoords = vec4(playerCoords.x, playerCoords.y, playerCoords.z, GetEntityHeading(cache.ped)) coords = type(coords) == 'table' and vec4(coords.x, coords.y, coords.z, coords.w or combinedCoords.w) or coords or combinedCoords model = type(model) == 'string' and joaat(model) or model if not IsModelInCdimage(model) then return end isnetworked = isnetworked == nil or isnetworked lib.requestModel(model) local veh = CreateVehicle(model, coords.x, coords.y, coords.z, coords.w, isnetworked, false) local netid = NetworkGetNetworkIdFromEntity(veh) SetVehicleHasBeenOwnedByPlayer(veh, true) SetNetworkIdCanMigrate(netid, true) SetModelAsNoLongerNeeded(model) if teleportInto then TaskWarpPedIntoVehicle(cache.ped, veh, -1) end if cb then cb(veh) end end --- Example local coords = RSGCore.Functions.GetCoords(PlayerPedId()) -- Ensure `coords` is vector4 with a heading value coords = vec4(coords.x, coords.y, coords.z, coords.w or GetEntityHeading(PlayerPedId())) RSGCore.Functions.SpawnVehicle('CART01', function(veh) SetEntityHeading(veh, coords.w) -- Set the heading of the vehicle TaskWarpPedIntoVehicle(PlayerPedId(), veh, -1) -- Teleport player into the vehicle end, coords, true) ``` ### RSGCore.Functions.DeleteVehicle * Deletes a vehicle at the given entity ID ```lua theme={null} function RSGCore.Functions.DeleteVehicle(vehicle) SetEntityAsMissionEntity(vehicle, true, true) DeleteVehicle(vehicle) end -- Example local ped = PlayerPedId() local veh = GetVehiclePedIsUsing(ped) if veh ~= 0 then RSGCore.Functions.DeleteVehicle(veh) else local pcoords = GetEntityCoords(ped) local vehicles = GetGamePool('CVehicle') for k, v in pairs(vehicles) do if #(pcoords - GetEntityCoords(v)) <= 5.0 then RSGCore.Functions.DeleteVehicle(v) end end end OR -- preferred method local ped = PlayerPedId() local veh = GetVehiclePedIsUsing(ped) if veh ~= 0 then SetEntityAsMissionEntity(veh, true, true) DeleteVehicle(veh) else local pcoords = GetEntityCoords(ped) local vehicles = GetGamePool('CVehicle') for k, v in pairs(vehicles) do if #(pcoords - GetEntityCoords(v)) <= 5.0 then SetEntityAsMissionEntity(v, true, true) DeleteVehicle(v) end end end ``` ### RSGCore.Functions.GetPlate * Get the license plate of a vehicle ```lua theme={null} function RSGCore.Functions.GetPlate(vehicle) if vehicle == 0 then return end return RSGCore.Shared.Trim(GetVehicleNumberPlateText(vehicle)) end -- Example local vehicle = GetVehiclePedIsIn(PlayerPedId(), false) local plate = RSGCore.Functions.GetPlate(vehicle) print('Vehicle plate: ' .. plate) ``` ### RSGCore.Functions.GetVehicleLabel * Get the display label/name of a vehicle ```lua theme={null} function RSGCore.Functions.GetVehicleLabel(vehicle) if vehicle == nil or vehicle == 0 then return end return GetLabelText(GetDisplayNameFromVehicleModel(GetEntityModel(vehicle))) end -- Example local vehicle = GetVehiclePedIsIn(PlayerPedId(), false) local label = RSGCore.Functions.GetVehicleLabel(vehicle) print('Vehicle name: ' .. label) ``` ### RSGCore.Functions.GetVehicleProperties * Get all properties of a vehicle (used for saving vehicle data) ```lua theme={null} function RSGCore.Functions.GetVehicleProperties(vehicle) if DoesEntityExist(vehicle) then -- Returns table with all vehicle properties return { model = GetEntityModel(vehicle), plate = RSGCore.Functions.GetPlate(vehicle), bodyHealth = GetVehicleBodyHealth(vehicle), engineHealth = GetVehicleEngineHealth(vehicle), fuelLevel = GetVehicleFuelLevel(vehicle), dirtLevel = GetVehicleDirtLevel(vehicle), color1 = colorPrimary, color2 = colorSecondary, -- and many more... } end end -- Example local vehicle = GetVehiclePedIsIn(PlayerPedId(), false) local props = RSGCore.Functions.GetVehicleProperties(vehicle) print(json.encode(props)) ``` ### RSGCore.Functions.SetVehicleProperties * Set all properties of a vehicle (used for loading saved vehicle data) ```lua theme={null} function RSGCore.Functions.SetVehicleProperties(vehicle, props) if DoesEntityExist(vehicle) then -- Sets all vehicle properties from the props table end end -- Example local vehicle = GetVehiclePedIsIn(PlayerPedId(), false) local props = { plate = 'NEWPLATE', bodyHealth = 1000.0, engineHealth = 1000.0, color1 = 12, color2 = 0 } RSGCore.Functions.SetVehicleProperties(vehicle, props) ``` ### RSGCore.Functions.LookAtEntity * Make the player ped look at an entity ```lua theme={null} ---@param entity number - The entity to look at ---@param timeout number - The time in milliseconds before the function times out ---@param speed number - The speed at which the entity should turn ---@return number - The time at which the entity was looked at function RSGCore.Functions.LookAtEntity(entity, timeout, speed) -- Smoothly turns player to face entity end -- Example local targetPed = GetClosestPed(coords) RSGCore.Functions.LookAtEntity(targetPed, 3000, 2.0) ``` ### RSGCore.Functions.PlayAnim * Play an animation on the player (deprecated - use ox\_lib) ```lua theme={null} ---@param animDict string - The name of the animation dictionary ---@param animName string - The name of the animation within the dictionary ---@param duration number - The duration of the animation in milliseconds. -1 will play indefinitely ---@param upperbodyOnly boolean - If true, only affects the upper body function RSGCore.Functions.PlayAnim(animDict, animName, upperbodyOnly, duration) local flags = upperbodyOnly and 16 or 0 local runTime = duration or -1 lib.playAnim(cache.ped, animDict, animName, 8.0, 3.0, runTime, flags, 0.0, false, false, true) end -- Example RSGCore.Functions.PlayAnim('amb_misc@world_human_smoke@male@male_b@idle_a', 'idle_a', false, -1) ``` ### RSGCore.Functions.IsWearingGloves * Check if the player is wearing gloves ```lua theme={null} function RSGCore.Functions.IsWearingGloves() local ped = PlayerPedId() local armIndex = GetPedDrawableVariation(ped, 3) local model = GetEntityModel(ped) if model == `mp_m_freemode_01` then if RSGCore.Shared.MaleNoGloves[armIndex] then return false end else if RSGCore.Shared.FemaleNoGloves[armIndex] then return false end end return true end -- Example if RSGCore.Functions.IsWearingGloves() then print('Player is wearing gloves - no fingerprints left') else print('Player is not wearing gloves - fingerprints left behind') end ``` ### RSGCore.Functions.GetObjects * Get all objects in the game world ```lua theme={null} function RSGCore.Functions.GetObjects() return GetGamePool('CObject') end -- Example local objects = RSGCore.Functions.GetObjects() for i = 1, #objects do local objCoords = GetEntityCoords(objects[i]) print('Object ' .. i .. ' at: ' .. objCoords) end ``` ### RSGCore.Functions.GetClosestPlayer * Get the closest player to the local player or coordinates ```lua theme={null} function RSGCore.Functions.GetClosestPlayer(coords) -- Returns closestPlayer (id), closestDistance end -- Example local closestPlayer, distance = RSGCore.Functions.GetClosestPlayer() if closestPlayer ~= -1 and distance < 3.0 then print('Closest player is ' .. distance .. ' units away') end ``` ### RSGCore.Functions.GetPeds * Get all peds in the game world with optional ignore list ```lua theme={null} function RSGCore.Functions.GetPeds(ignoreList) local pedPool = GetGamePool('CPed') local peds = {} local ignoreTable = {} ignoreList = ignoreList or {} for i = 1, #ignoreList do ignoreTable[ignoreList[i]] = true end for i = 1, #pedPool do if not ignoreTable[pedPool[i]] then peds[#peds + 1] = pedPool[i] end end return peds end -- Example local peds = RSGCore.Functions.GetPeds({PlayerPedId()}) -- Get all peds except player for i = 1, #peds do print('Ped ' .. i .. ': ' .. peds[i]) end ``` ### RSGCore.Functions.GetClosestPed * Get the closest ped to player or coordinates ```lua theme={null} function RSGCore.Functions.GetClosestPed(coords, ignoreList) -- Returns closestPed, closestDistance end -- Example local closestPed, distance = RSGCore.Functions.GetClosestPed(nil, {PlayerPedId()}) if closestPed ~= -1 then print('Closest ped is ' .. distance .. ' units away') end ``` ### RSGCore.Functions.GetClosestObject * Get the closest object to player or coordinates ```lua theme={null} function RSGCore.Functions.GetClosestObject(coords) -- Returns closestObject, closestDistance end -- Example local coords = GetEntityCoords(PlayerPedId()) local closestObject, distance = RSGCore.Functions.GetClosestObject(coords) if closestObject ~= -1 then print('Closest object is ' .. distance .. ' units away') end ``` ### RSGCore.Functions.SpawnClear * Check if an area is clear of vehicles for spawning ```lua theme={null} function RSGCore.Functions.SpawnClear(coords, radius) if coords then coords = type(coords) == 'table' and vec3(coords.x, coords.y, coords.z) or coords else coords = GetEntityCoords(PlayerPedId()) end local vehicles = GetGamePool('CVehicle') local closeVeh = {} for i = 1, #vehicles, 1 do local vehicleCoords = GetEntityCoords(vehicles[i]) local distance = #(vehicleCoords - coords) if distance <= radius then closeVeh[#closeVeh + 1] = vehicles[i] end end if #closeVeh > 0 then return false end return true end -- Example local coords = GetEntityCoords(PlayerPedId()) if RSGCore.Functions.SpawnClear(coords, 5.0) then print('Area is clear for spawning') else print('Area has vehicles blocking spawn') end ``` ### RSGCore.Functions.GetCardinalDirection * Get the cardinal direction an entity is facing ```lua theme={null} function RSGCore.Functions.GetCardinalDirection(entity) entity = DoesEntityExist(entity) and entity or PlayerPedId() if DoesEntityExist(entity) then local heading = GetEntityHeading(entity) if ((heading >= 0 and heading < 45) or (heading >= 315 and heading < 360)) then return 'North' elseif (heading >= 45 and heading < 135) then return 'West' elseif (heading >= 135 and heading < 225) then return 'South' elseif (heading >= 225 and heading < 315) then return 'East' end else return 'Cardinal Direction Error' end end -- Example local direction = RSGCore.Functions.GetCardinalDirection(PlayerPedId()) print('You are facing: ' .. direction) ``` ### RSGCore.Functions.GetStreetNametAtCoords * Get street names at coordinates ```lua theme={null} function RSGCore.Functions.GetStreetNametAtCoords(coords) local streetname1, streetname2 = GetStreetNameAtCoord(coords.x, coords.y, coords.z) return { main = GetStreetNameFromHashKey(streetname1), cross = GetStreetNameFromHashKey(streetname2) } end -- Example local coords = GetEntityCoords(PlayerPedId()) local streets = RSGCore.Functions.GetStreetNametAtCoords(coords) print('Main street: ' .. streets.main) print('Cross street: ' .. streets.cross) ``` ### RSGCore.Functions.GetZoneAtCoords * Get the zone/area name at coordinates ```lua theme={null} function RSGCore.Functions.GetZoneAtCoords(coords) return GetLabelText(GetNameOfZone(coords)) end -- Example local coords = GetEntityCoords(PlayerPedId()) local zone = RSGCore.Functions.GetZoneAtCoords(coords) print('Current zone: ' .. zone) ``` ### RSGCore.Functions.GetCurrentTime * Get the current in-game time ```lua theme={null} function RSGCore.Functions.GetCurrentTime() local obj = {} obj.min = GetClockMinutes() obj.hour = GetClockHours() if obj.hour <= 12 then obj.ampm = 'AM' elseif obj.hour >= 13 then obj.ampm = 'PM' obj.formattedHour = obj.hour - 12 end if obj.min <= 9 then obj.formattedMin = '0' .. obj.min end return obj end -- Example local time = RSGCore.Functions.GetCurrentTime() print('Time: ' .. (time.formattedHour or time.hour) .. ':' .. (time.formattedMin or time.min) .. ' ' .. time.ampm) ``` ### RSGCore.Functions.GetGroundZCoord * Get the ground Z coordinate at given coordinates ```lua theme={null} function RSGCore.Functions.GetGroundZCoord(coords) if not coords then return end local retval, groundZ = GetGroundZFor_3dCoord(coords.x, coords.y, coords.z, 0) if retval then return vector3(coords.x, coords.y, groundZ) else return coords end end -- Example local coords = GetEntityCoords(PlayerPedId()) local groundCoords = RSGCore.Functions.GetGroundZCoord(coords) print('Ground Z: ' .. groundCoords.z) ``` # ๐Ÿฎ Overextended Library Source: https://rsg.mintlify.app/api-reference/endpoint/oxlibreference A standalone library for providing easily reusable code as importable modules and exports. ## Installation To enable the ox\_lib library inside of your resource, add `@ox_lib/init.lua` as a shared\_script in your fxmanifest.lua file: ```lua fxmanifest.lua theme={null} fx_version 'cerulean' game 'rdr3' shared_scripts { '@ox_lib/init.lua', } ``` Make sure ox\_lib is started before any resources that depend on it in your server.cfg! *** ## Building the UI For advanced UI building with ox\_lib, please visit the official documentation: * **Ox\_Lib Docs**: [https://overextended.dev/ox\_lib#building-the-ui](https://overextended.dev/ox_lib#building-the-ui) * **UI Components**: [https://overextended.dev/ox\_lib/Interface/Client/context](https://overextended.dev/ox_lib/Interface/Client/context) * **Input Dialogs**: [https://overextended.dev/ox\_lib/Modules/Interface/Client/input](https://overextended.dev/ox_lib/Modules/Interface/Client/input) *** ## Context Menus Context menus provide an intuitive way to display multiple options to players. ### Registering a Context Menu Use `lib.registerContext` to define a menu's structure: ```lua theme={null} lib.registerContext({ id = 'example_menu', title = 'Example Menu', options = { { title = 'Open Inventory', description = 'View your inventory items.', icon = 'fa-solid fa-box', iconColor = '#C53030', event = 'inventory:client:open', arrow = true }, { title = 'Toggle Duty', description = 'Clock in or out of duty', icon = 'fa-solid fa-shield', iconColor = '#48BB78', event = 'job:client:toggleDuty', arrow = true }, { title = 'Check Money', description = 'View your current balance', icon = 'fa-solid fa-dollar-sign', iconColor = '#F6E05E', onSelect = function() local PlayerData = RSGCore.Functions.GetPlayerData() local cash = PlayerData.money.cash lib.notify({ title = 'Bank Balance', description = 'You have $'..cash, type = 'success' }) end }, { title = 'Open Sub Menu', description = 'Navigate to another menu', icon = 'fa-solid fa-arrow-right', menu = 'sub_menu_id', -- Opens another registered menu arrow = true } } }) ``` ### Menu Options Properties * **title** `string` - The display text for the option * **description** `string` (optional) - Additional information shown below the title * **icon** `string` (optional) - Font Awesome icon class (e.g., `'fa-solid fa-box'`) * **iconColor** `string` (optional) - Hex color for the icon (e.g., `'#C53030'`) * **event** `string` (optional) - Client event to trigger when selected * **serverEvent** `string` (optional) - Server event to trigger when selected * **onSelect** `function` (optional) - Function to execute when selected * **args** `any` (optional) - Arguments to pass to the event/function * **arrow** `boolean` (optional) - Shows an arrow indicator * **menu** `string` (optional) - ID of another menu to open * **disabled** `boolean` (optional) - Greys out and disables the option * **metadata** `table` (optional) - Additional data displayed on the right side ### Showing a Menu Display a registered menu using `lib.showContext`: ```lua theme={null} lib.showContext('example_menu') ``` ### Complete Example ```lua theme={null} -- Register main menu lib.registerContext({ id = 'police_menu', title = 'Law Enforcement Menu', options = { { title = 'Check ID', description = 'View citizen identification', icon = 'fa-solid fa-id-card', event = 'police:client:checkId', arrow = true }, { title = 'Search Player', description = 'Search nearby citizen', icon = 'fa-solid fa-magnifying-glass', event = 'police:client:searchPlayer', arrow = true }, { title = 'Jail Options', description = 'Access jail system', icon = 'fa-solid fa-handcuffs', menu = 'jail_submenu', arrow = true } } }) -- Register sub-menu lib.registerContext({ id = 'jail_submenu', title = 'Jail Menu', menu = 'police_menu', -- Back button returns to this menu options = { { title = 'Send to Jail', icon = 'fa-solid fa-lock', serverEvent = 'police:server:jailPlayer', args = { time = 300 } }, { title = 'Release from Jail', icon = 'fa-solid fa-unlock', serverEvent = 'police:server:releasePlayer' } } }) -- Show the menu lib.showContext('police_menu') ``` *** ## Notifications Custom notifications with extensive styling options. ### Client-Side Notifications ```lua theme={null} lib.notify({ title = 'Success!', description = 'You have received $500', type = 'success', icon = 'fa-solid fa-dollar-sign', iconColor = '#48BB78', duration = 5000, position = 'top-right' }) ``` ### Server-Side Notifications ```lua theme={null} TriggerClientEvent('ox_lib:notify', source, { title = 'Error!', description = 'You do not have permission', type = 'error', icon = 'fa-solid fa-triangle-exclamation', iconAnimation = 'shake', duration = 7000 }) ``` ### Notification Properties * **title** `string` (optional) - The notification title * **description** `string` - The main notification message * **type** `string` - Type of notification: `'success'`, `'error'`, `'warning'`, `'info'` * **icon** `string` (optional) - Font Awesome icon class * **iconColor** `string` (optional) - Hex color for the icon * **iconAnimation** `string` (optional) - Animation: `'spin'`, `'shake'`, `'beat'`, `'fade'`, `'bounce'` * **duration** `number` (optional) - Duration in milliseconds (default: 5000) * **position** `string` (optional) - Position: `'top'`, `'top-right'`, `'top-left'`, `'bottom'`, `'bottom-right'`, `'bottom-left'`, `'center-right'`, `'center-left'` ### Notification Types Examples ```lua theme={null} -- Success lib.notify({ title = 'Item Purchased', description = 'You bought a canteen for $15', type = 'success' }) -- Error lib.notify({ title = 'Purchase Failed', description = 'Not enough money', type = 'error' }) -- Warning lib.notify({ title = 'Low Hunger', description = 'Your hunger is getting low', type = 'warning' }) -- Info lib.notify({ title = 'Server Restart', description = 'Server will restart in 10 minutes', type = 'info' }) ``` *** ## Input Dialogs Request user input with customizable forms. ### Basic Input Dialog ```lua theme={null} local input = lib.inputDialog('Horse Name', { { type = 'input', label = 'Horse Name', description = 'Enter a name for your horse', required = true, min = 3, max = 20 } }) if input then local horseName = input[1] print('Horse named: ' .. horseName) end ``` ### Multi-Field Input ```lua theme={null} local input = lib.inputDialog('Player Report', { { type = 'input', label = 'Player ID', description = 'Enter the player server ID', required = true, icon = 'fa-solid fa-hashtag' }, { type = 'select', label = 'Report Type', description = 'Select the type of report', required = true, options = { { value = 'rdm', label = 'Random Deathmatch' }, { value = 'vdm', label = 'Vehicle Deathmatch' }, { value = 'exploit', label = 'Exploiting' }, { value = 'other', label = 'Other' } }, icon = 'fa-solid fa-list' }, { type = 'textarea', label = 'Description', description = 'Describe what happened', required = true, min = 10, max = 500, icon = 'fa-solid fa-pen' }, }) if input then local playerId = input[1] local reportType = input[2] local description = input[3] TriggerServerEvent('admin:server:createReport', playerId, reportType, description) end ``` ### Input Types **Text Input**: ```lua theme={null} { type = 'input', label = 'Name', placeholder = 'John Doe', required = true, min = 3, max = 50 } ``` **Number Input**: ```lua theme={null} { type = 'number', label = 'Amount', placeholder = '100', required = true, min = 1, max = 1000 } ``` **Select Dropdown**: ```lua theme={null} { type = 'select', label = 'Choose Option', options = { { value = 'option1', label = 'Option 1' }, { value = 'option2', label = 'Option 2' } } } ``` **Multi-Select**: ```lua theme={null} { type = 'multi-select', label = 'Select Multiple', options = { { value = 'opt1', label = 'Option 1' }, { value = 'opt2', label = 'Option 2' }, { value = 'opt3', label = 'Option 3' } } } ``` **Checkbox**: ```lua theme={null} { type = 'checkbox', label = 'Accept Terms', required = true } ``` **Textarea**: ```lua theme={null} { type = 'textarea', label = 'Long Description', min = 10, max = 500 } ``` **Date Picker**: ```lua theme={null} { type = 'date', label = 'Birth Date', format = 'DD/MM/YYYY' } ``` **Time Picker**: ```lua theme={null} { type = 'time', label = 'Meeting Time', format = '24' } ``` *** ## Progress Bars Display progress for actions. ### Basic Progress Bar ```lua theme={null} if lib.progressBar({ duration = 5000, label = 'Cooking meal...', useWhileDead = false, canCancel = true, disable = { move = true, car = true, combat = true }, }) then -- Action completed lib.notify({ description = 'Meal cooked!', type = 'success' }) else -- Action cancelled lib.notify({ description = 'Cooking cancelled', type = 'error' }) end ``` ### Progress with Animation ```lua theme={null} if lib.progressBar({ duration = 3000, label = 'Fishing...', useWhileDead = false, canCancel = true, disable = { move = true, }, anim = { dict = 'amb_work@world_human_box_pickup@1@male_a@stand_exit_withprop', clip = 'exit_front' }, }) then -- Fishing complete end ``` *** ## Localization Text elements support multi-language via locale files. ### Setup Localization 1. Add to fxmanifest.lua: ```lua theme={null} ox_lib 'locale' files { 'locales/*.json', } ``` 2. Create locale files (e.g., `locales/en.json`): ```json theme={null} { "horse_name": "Horse Name", "horse_desc": "Enter a name for your horse", "purchase_success": "Purchase successful!", "not_enough_money": "You don't have enough money" } ``` 3. Use in code: ```lua theme={null} lib.notify({ title = lib.locale('purchase_success'), description = lib.locale('not_enough_money'), type = 'error' }) ``` Always use locales for multi-language support! Make sure to call `lib.locale()` at the top of your script if needed. *** ## Alert Dialogs Simple confirmation dialogs. ```lua theme={null} local alert = lib.alertDialog({ header = 'Confirm Purchase', content = 'Are you sure you want to buy this horse for $500?', centered = true, cancel = true, labels = { confirm = 'Buy', cancel = 'Cancel' } }) if alert == 'confirm' then -- Player confirmed TriggerServerEvent('horses:server:buyHorse') end ``` *** ## Useful Utilities ### Request Model ```lua theme={null} local model = `A_C_Horse_AmericanPaint_Overo` lib.requestModel(model, 5000) -- 5 second timeout -- Use model local horse = CreatePed(model, coords.x, coords.y, coords.z, heading, true, false, false, false) -- Clean up SetModelAsNoLongerNeeded(model) ``` ### Request Animation Dictionary ```lua theme={null} lib.requestAnimDict('amb_work@world_human_box_pickup@1@male_a@stand_exit_withprop', 5000) -- Use animation TaskPlayAnim(ped, 'amb_work@world_human_box_pickup@1@male_a@stand_exit_withprop', 'exit_front', 8.0, -8.0, -1, 0, 0, false, false, false) -- Clean up RemoveAnimDict('amb_work@world_human_box_pickup@1@male_a@stand_exit_withprop') ``` *** ## Best Practices **Use context menus for multiple options**: They provide a better UX than command-based systems **Always validate user input**: Never trust client-side input on the server without validation **Use locales from the start**: It's easier to add translations early than to retrofit them later ### Performance Tips 1. **Request resources once**: Don't request the same model/animation repeatedly 2. **Clean up resources**: Always call `SetModelAsNoLongerNeeded` and `RemoveAnimDict` 3. **Use progress bars for long actions**: Improves player experience 4. **Cache frequently used data**: Don't query the same data repeatedly *** For more advanced features, visit the official ox\_lib documentation: [https://overextended.dev/ox\_lib](https://overextended.dev/ox_lib) # ๐Ÿ‘๏ธ Overextended Target Source: https://rsg.mintlify.app/api-reference/endpoint/oxtargetreference A performant and flexible standalone targeting resource or third-eye, with additional functionality for Cfx.re. ## Target Options * label: `string` * name?: `string` * * An identifier used when removing an option. * icon?: `string` * * Name of a Font Awesome icon. * iconColor?: `string` * distance?: `number` * * The max distance to display the option. * bones?: `string` or `string[]` * * A bone name or array of bone names (see [GetEntityBoneIndexByName](https://rdr3natives.com/?_0xBACA8FE9C76C124E)). * offset?: `vector3` * * Offset the targetable area of an entity, relative to the model dimensions. * offsetAbsolute?: `vector3` * * Offset the targetable area of an entity, relative to the entity's world coords. * offsetSize?: `number` * * The radius of the targetable area for an entity offset. * groups?: `string` or `string[]` or `table` * * A group, array of groups, or pairs of groups-grades required to show the option. * * Groups are framework dependent, and may refer to jobs, gangs, etc. * items?: `string` or `string[]` or `table` * * An item, array of items, or pairs of items-count required to show the option. * * Items are framework dependent. * anyItem?: `boolean` * * Only require a single item from the items table to exist. * canInteract?: `function(entity, distance, coords, name, bone)` * * Options will always display if this is undefined. * menuName?: `string` * * The option is only displayed when a menu has been set with openMenu. * openMenu?: string * * Sets the current menu name, displaying only options for the menuName. * onSelect?: `function(data)` * export?: `string` * event?: `string` * serverEvent?: `string` * command?: `string` *** ## Overview ox\_target (previously known as qtarget) is a performant and flexible targeting resource for RedM. It allows players to interact with entities, zones, and models using a "third-eye" targeting system. ox\_target is already included and used extensively in RSG Framework resources! *** ## Installation ox\_target is already included in RSG Framework. To use it in your custom resources: ```lua fxmanifest.lua theme={null} dependencies { 'ox_target' } ``` *** ## Entity Targeting ### addEntity Add targeting options to a specific entity. ```lua theme={null} exports.ox_target:addEntity(entity, options) ``` **Parameters**: * `entity` (number) - The entity handle * `options` (table) - Array of target options **Example**: ```lua theme={null} local npc = CreatePed(model, coords.x, coords.y, coords.z, heading, true, false, false, false) exports.ox_target:addEntity(npc, { { label = 'Talk to Shopkeeper', icon = 'fa-solid fa-comments', distance = 2.5, onSelect = function(data) print('Talking to shopkeeper') -- Open shop menu end }, { label = 'Rob Shopkeeper', icon = 'fa-solid fa-mask', distance = 2.0, canInteract = function(entity, distance, coords, name, bone) local Player = RSGCore.Functions.GetPlayerData() return Player.job.name ~= 'vallaw' end, onSelect = function(data) -- Trigger robbery TriggerEvent('robbery:client:start') end } }) ``` *** ### removeEntity Remove targeting options from a specific entity. ```lua theme={null} exports.ox_target:removeEntity(entity, optionNames) ``` **Parameters**: * `entity` (number) - The entity handle * `optionNames` (string|table|nil) - Specific option names to remove, or nil to remove all **Example**: ```lua theme={null} -- Remove specific option exports.ox_target:removeEntity(npc, 'talk_option') -- Remove all options exports.ox_target:removeEntity(npc) ``` *** ## Model Targeting ### addModel Add targeting options to all entities with specific models. ```lua theme={null} exports.ox_target:addModel(models, options) ``` **Parameters**: * `models` (string|number|table) - Model hash(es) or name(s) * `options` (table) - Array of target options **Example**: ```lua theme={null} -- Target all hitching posts exports.ox_target:addModel(`P_HITCHINGPOST01X`, { { label = 'Hitch Horse', icon = 'fa-solid fa-horse', distance = 3.0, canInteract = function(entity, distance, coords, name, bone) -- Check if player is on a horse return IsPedOnMount(PlayerPedId()) end, onSelect = function(data) TriggerEvent('horses:client:hitchHorse', data.entity) end } }) -- Multiple models exports.ox_target:addModel({ `P_HITCHINGPOST01X`, `P_HITCHINGPOST02X`, `P_HITCHINGPOST03X` }, { { label = 'Hitch Horse', icon = 'fa-solid fa-horse', distance = 3.0, onSelect = function(data) TriggerEvent('horses:client:hitchHorse', data.entity) end } }) ``` *** ### removeModel Remove targeting options from models. ```lua theme={null} exports.ox_target:removeModel(models, optionNames) ``` **Parameters**: * `models` (string|number|table) - Model hash(es) or name(s) * `optionNames` (string|table|nil) - Option names to remove, or nil for all **Example**: ```lua theme={null} exports.ox_target:removeModel(`P_HITCHINGPOST01X`) ``` *** ## Zone Targeting ### addBoxZone Add a box-shaped targeting zone. ```lua theme={null} exports.ox_target:addBoxZone(name, coords, size, rotation, options, targetoptions) ``` **Parameters**: * `name` (string) - Unique zone identifier * `coords` (vector3) - Center coordinates * `size` (vector3) - Box dimensions (length, width, height) * `rotation` (number) - Rotation in degrees * `options` (table) - Array of target options * `targetoptions` (table) - Additional zone settings **Example**: ```lua theme={null} exports.ox_target:addBoxZone('valentine_bank', vector3(-308.36, 775.58, 118.70), vector3(2.0, 2.0, 2.0), 0, { { label = 'Access Bank', icon = 'fa-solid fa-piggy-bank', onSelect = function() TriggerEvent('rsg-banking:client:openBank', 'valentine') end } }) ``` *** ### addSphereZone Add a sphere-shaped targeting zone. ```lua theme={null} exports.ox_target:addSphereZone(name, coords, radius, options, targetoptions) ``` **Parameters**: * `name` (string) - Unique zone identifier * `coords` (vector3) - Center coordinates * `radius` (number) - Sphere radius * `options` (table) - Array of target options * `targetoptions` (table) - Additional zone settings **Example**: ```lua theme={null} exports.ox_target:addSphereZone('butcher_shop', vector3(-301.12, 800.34, 118.90), 2.5, { { label = 'Sell Meat', icon = 'fa-solid fa-meat', canInteract = function() return exports['rsg-inventory']:HasItem(source, 'meat') end, onSelect = function() TriggerServerEvent('butcher:server:sellMeat') end } }) ``` *** ### removeZone Remove a targeting zone. ```lua theme={null} exports.ox_target:removeZone(name) ``` **Parameters**: * `name` (string) - Zone identifier **Example**: ```lua theme={null} exports.ox_target:removeZone('valentine_bank') ``` *** ## Advanced Options ### Job Restrictions Restrict interactions to specific jobs: ```lua theme={null} { label = 'Access Evidence Locker', icon = 'fa-solid fa-box', groups = 'vallaw', -- Single job onSelect = function() -- Open evidence locker end } -- Multiple jobs { label = 'Access Medical Supplies', icon = 'fa-solid fa-briefcase-medical', groups = {'doctor', 'vallaw'}, -- Array of jobs onSelect = function() -- Open supplies end } -- Job with grade requirement { label = 'Access Sheriff Office', icon = 'fa-solid fa-door-open', groups = { vallaw = 2 -- Valentine Law grade 2 or higher }, onSelect = function() -- Open office end } ``` *** ### Item Requirements Require specific items to see the interaction: ```lua theme={null} { label = 'Repair Wagon', icon = 'fa-solid fa-wrench', items = 'repair_kit', -- Single item onSelect = function() -- Repair wagon end } -- Multiple items (requires all) { label = 'Cook Stew', icon = 'fa-solid fa-pot', items = {'meat', 'vegetables', 'water'}, onSelect = function() -- Cook stew end } -- Items with quantity { label = 'Craft Bandage', icon = 'fa-solid fa-bandage', items = { cloth = 3, thread = 1 }, onSelect = function() -- Craft bandage end } -- Require ANY item (not all) { label = 'Feed Horse', icon = 'fa-solid fa-carrot', items = {'apple', 'carrot', 'hay'}, anyItem = true, -- Only needs one of these items onSelect = function() -- Feed horse end } ``` *** ### Distance Control Control interaction distance: ```lua theme={null} { label = 'Open Door', icon = 'fa-solid fa-door-open', distance = 2.0, -- Can interact from 2 units away onSelect = function() -- Open door end } ``` *** ### Bone Targeting Target specific entity bones: ```lua theme={null} { label = 'Pat Horse', icon = 'fa-solid fa-hand', bones = 'neck', -- Single bone distance = 2.0, onSelect = function(data) -- Pat horse end } -- Multiple bones { label = 'Check Saddle', icon = 'fa-solid fa-saddle', bones = {'saddle', 'back'}, distance = 2.0, onSelect = function(data) -- Check saddle end } ``` *** ### Can Interact Function Dynamic interaction visibility: ```lua theme={null} { label = 'Lockpick Door', icon = 'fa-solid fa-lock', canInteract = function(entity, distance, coords, name, bone) -- Check if player has lockpick local hasLockpick = exports['rsg-inventory']:HasItem(source, 'lockpick') -- Check if not a cop local Player = RSGCore.Functions.GetPlayerData() local isCop = Player.job.type == 'leo' return hasLockpick and not isCop end, onSelect = function(data) -- Start lockpicking end } ``` *** ### Event Types Different ways to handle interactions: ```lua theme={null} -- Client Event { label = 'Open Menu', icon = 'fa-solid fa-bars', event = 'myresource:client:openMenu' -- Triggers client event } -- Server Event { label = 'Purchase Item', icon = 'fa-solid fa-shopping-cart', serverEvent = 'shop:server:purchase', -- Triggers server event args = { item = 'bread', price = 5 } -- Arguments passed to event } -- OnSelect Function { label = 'Custom Action', icon = 'fa-solid fa-cog', onSelect = function(data) -- data.entity = entity handle -- data.coords = entity coordinates -- data.model = entity model -- Custom code here end } -- Export { label = 'Use Export', icon = 'fa-solid fa-box', export = 'myresource:openThing' -- Calls an export } -- Command { label = 'Run Command', icon = 'fa-solid fa-terminal', command = 'emote wave' -- Executes a command } ``` *** ## Complete Examples ### Example 1: NPC Shopkeeper ```lua theme={null} CreateThread(function() -- Create NPC local model = `U_M_M_VALTHESKINNER_01` lib.requestModel(model, 5000) local coords = vector3(-324.28, 803.50, 117.88) local npc = CreatePed(model, coords.x, coords.y, coords.z, 90.0, false, false, false, false) SetEntityCanBeDamaged(npc, false) SetEntityInvincible(npc, true) FreezeEntityPosition(npc, true) SetBlockingOfNonTemporaryEvents(npc, true) -- Add targeting exports.ox_target:addEntity(npc, { { label = 'Browse Goods', icon = 'fa-solid fa-shopping-basket', distance = 2.5, onSelect = function() TriggerServerEvent('shop:server:open', 'general') end }, { label = 'Sell Items', icon = 'fa-solid fa-dollar-sign', distance = 2.5, canInteract = function() -- Only show if player has items to sell return exports['rsg-inventory']:GetItemCount(source, {'meat', 'pelt'}) > 0 end, onSelect = function() TriggerEvent('shop:client:sellMenu') end } }) end) ``` *** ### Example 2: Job-Restricted Zones ```lua theme={null} -- Sheriff's Office Door exports.ox_target:addBoxZone('sheriff_office', vector3(-275.42, 807.12, 119.38), vector3(1.5, 1.5, 2.5), 0, { { label = 'Enter Office', icon = 'fa-solid fa-door-open', groups = { vallaw = 0 -- Any valentine law grade }, onSelect = function() -- Unlock and open door TriggerEvent('doors:client:open', 'sheriff_office') end } }) -- Evidence Locker (high rank only) exports.ox_target:addBoxZone('evidence_locker', vector3(-270.11, 810.55, 119.38), vector3(2.0, 2.0, 2.0), 0, { { label = 'Access Evidence', icon = 'fa-solid fa-box', groups = { vallaw = 3 -- Grade 3 or higher }, onSelect = function() TriggerServerEvent('police:server:openEvidence') end } }) ``` *** ### Example 3: Crafting Station ```lua theme={null} exports.ox_target:addSphereZone('crafting_bench', vector3(-280.50, 815.22, 119.50), 2.0, { { label = 'Craft Bandages', icon = 'fa-solid fa-bandage', items = { cloth = 2, thread = 1 }, onSelect = function() TriggerEvent('crafting:client:start', 'bandage') end }, { label = 'Craft Repair Kit', icon = 'fa-solid fa-toolbox', items = { metal = 5, wood = 3, oil = 1 }, onSelect = function() TriggerEvent('crafting:client:start', 'repair_kit') end }, { label = 'Craft Lockpick', icon = 'fa-solid fa-key', items = { metal = 2 }, canInteract = function() local Player = RSGCore.Functions.GetPlayerData() return Player.metadata.rep.crafting and Player.metadata.rep.crafting >= 10 end, onSelect = function() TriggerEvent('crafting:client:start', 'lockpick') end } }) ``` *** ### Example 4: Dynamic Hitching Posts ```lua theme={null} -- Target all hitching post models local hitchingModels = { `P_HITCHINGPOST01X`, `P_HITCHINGPOST02X`, `P_HITCHINGPOST03X`, `P_HITCHINGPOST04X`, `P_HITCHINGPOSTOLD01X` } exports.ox_target:addModel(hitchingModels, { { label = 'Hitch Horse', icon = 'fa-solid fa-horse', distance = 3.5, canInteract = function(entity, distance, coords, name, bone) return IsPedOnMount(PlayerPedId()) end, onSelect = function(data) local horse = GetMount(PlayerPedId()) if horse and horse ~= 0 then TriggerServerEvent('horses:server:hitchHorse', NetworkGetNetworkIdFromEntity(horse), data.coords) end end }, { label = 'Retrieve Horse', icon = 'fa-solid fa-hand-holding', distance = 3.5, canInteract = function(entity, distance, coords, name, bone) -- Check if player has a horse hitched nearby return not IsPedOnMount(PlayerPedId()) -- Not on horse end, onSelect = function(data) TriggerServerEvent('horses:server:retrieveHorse', data.coords) end } }) ``` *** ## Best Practices **Use canInteract for dynamic visibility**: Hide options that aren't currently available instead of showing disabled options **Always validate on server**: Never trust client-side data. Always re-check permissions and items on the server **Use appropriate distances**: Keep interaction distances realistic (1.5-3.0 for most interactions) ### Performance Tips 1. **Don't add too many zones**: Each zone checks distance every frame 2. **Use models over entities**: Model targeting is more efficient than entity targeting for common objects 3. **Efficient canInteract**: Keep canInteract functions lightweight 4. **Clean up when done**: Remove zones/entities when they're no longer needed *** ## Troubleshooting * Check distance - are you close enough? * Verify canInteract function isn't returning false * Check job/gang/item requirements * Ensure ox\_target is started before your resource * Verify the groups parameter is set correctly * Check player's actual job name (not label) * Ensure grade requirements are correct * Check zone coordinates are correct * Verify size/radius is appropriate * Make sure zone name is unique * Check for Lua errors in F8 console *** For more advanced usage, check the official ox\_target documentation: [https://overextended.dev/ox\_target](https://overextended.dev/ox_target) # ๐Ÿคต Player Information Source: https://rsg.mintlify.app/api-reference/endpoint/playerinformationreference Complete guide to accessing and using player information in RSG Framework ## Introduction Player information is the core data structure that defines everything about a player in RSG Framework. Understanding how to access and manipulate this data is essential for creating any meaningful gameplay feature. PlayerData contains all information about a player: identity, job, gang, money, inventory, metadata, and more! *** ## How It Works ### Getting Player Object **Server-Side:** ```lua theme={null} -- SERVER SIDE local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end -- Now you have access to all player data local citizenid = Player.PlayerData.citizenid ``` **Client-Side:** ```lua theme={null} -- CLIENT SIDE local RSGCore = exports['rsg-core']:GetCoreObject() local PlayerData = RSGCore.Functions.GetPlayerData() -- Now you have access to local player data local firstname = PlayerData.charinfo.firstname ``` **Server-side**: Always validate that `Player` exists before using it! **Client-side**: Make sure player is loaded (`RSGCore:Client:OnPlayerLoaded`) before accessing PlayerData! *** ## PlayerData Structure The complete PlayerData object structure: ```lua theme={null} PlayerData = { source = number, -- Player's server ID citizenid = string, -- Unique citizen identifier cid = number, -- Character ID in database license = string, -- Player's RockstarGames license name = string, -- Player's server name charinfo = table, -- Character information money = table, -- Player's money (all types) job = table, -- Current job gang = table, -- Current gang metadata = table, -- Player stats/metadata items = table, -- Inventory items position = vector3, -- Last saved position Offline = boolean -- If player is offline (for offline player operations) } ``` *** ## Character Information ### charinfo Structure ```lua theme={null} PlayerData.charinfo = { firstname = string, -- First name lastname = string, -- Last name birthdate = string, -- Date of birth (MM-DD-YYYY) gender = number, -- Gender (0 = male, 1 = female) nationality = string,-- Nationality account = string, -- Bank account number phone = string, -- Phone number backstory = string -- Character backstory } ``` ### Accessing Character Info **Server-Side:** ```lua theme={null} -- SERVER SIDE local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end local fullName = Player.PlayerData.charinfo.firstname .. ' ' .. Player.PlayerData.charinfo.lastname local birthdate = Player.PlayerData.charinfo.birthdate local gender = Player.PlayerData.charinfo.gender == 0 and 'Male' or 'Female' print(fullName, birthdate, gender) ``` **Client-Side:** ```lua theme={null} -- CLIENT SIDE local RSGCore = exports['rsg-core']:GetCoreObject() RegisterNetEvent('RSGCore:Client:OnPlayerLoaded', function() local PlayerData = RSGCore.Functions.GetPlayerData() lib.notify({ title = 'Welcome!', description = 'Hello, ' .. PlayerData.charinfo.firstname, type = 'success' }) end) ``` **Complete Example - Identity Card:** ```lua theme={null} -- SERVER SIDE RegisterNetEvent('identity:server:showCard', function(targetId) local src = source local Player = RSGCore.Functions.GetPlayer(src) local Target = RSGCore.Functions.GetPlayer(targetId) if not Player or not Target then return end local cardData = { name = Player.PlayerData.charinfo.firstname .. ' ' .. Player.PlayerData.charinfo.lastname, dob = Player.PlayerData.charinfo.birthdate, gender = Player.PlayerData.charinfo.gender == 0 and 'Male' or 'Female', nationality = Player.PlayerData.charinfo.nationality, citizenid = Player.PlayerData.citizenid } TriggerClientEvent('identity:client:showCard', targetId, cardData) end) ``` *** ## Money System ### money Structure ```lua theme={null} PlayerData.money = { cash = number, -- Cash on hand bank = number, -- Bank account bloodmoney = number, -- Blood money (criminal currency) valbank = number, -- Valentine bank rhobank = number, -- Rhodes bank blkbank = number, -- Blackwater bank stdbank = number -- Saint Denis bank } ``` ### Accessing Money **Server-Side:** ```lua theme={null} -- SERVER SIDE local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end -- Get specific money type local cash = Player.Functions.GetMoney('cash') local bank = Player.Functions.GetMoney('bank') -- Get all money local allMoney = Player.PlayerData.money print('Cash: $' .. cash) print('Bank: $' .. bank) print('Total: $' .. (cash + bank)) ``` **Client-Side:** ```lua theme={null} -- CLIENT SIDE local RSGCore = exports['rsg-core']:GetCoreObject() local PlayerData = RSGCore.Functions.GetPlayerData() local cash = PlayerData.money.cash local bank = PlayerData.money.bank print('You have $' .. cash .. ' cash and $' .. bank .. ' in bank') ``` **Complete Example - Money Display:** ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Player:SetPlayerData', function(newData) local oldMoney = RSGCore.PlayerData.money or {} RSGCore.PlayerData = newData -- Check for money changes for moneyType, amount in pairs(newData.money) do if oldMoney[moneyType] and oldMoney[moneyType] ~= amount then local difference = amount - oldMoney[moneyType] if difference > 0 then lib.notify({ description = '+$' .. difference .. ' ' .. moneyType, type = 'success' }) elseif difference < 0 then lib.notify({ description = '-$' .. math.abs(difference) .. ' ' .. moneyType, type = 'error' }) end end end end) ``` *** ## Job System ### job Structure ```lua theme={null} PlayerData.job = { name = string, -- Job name (e.g., 'police') label = string, -- Job display name (e.g., 'Police Department') payment = number, -- Payment per paycheck onduty = boolean, -- If player is on duty isboss = boolean, -- If player is boss grade = { name = string, -- Grade name (e.g., 'chief') level = number -- Grade level (0-10) }, type = string -- Job type (e.g., 'leo', 'ems') } ``` ### Accessing Job Info **Server-Side:** ```lua theme={null} -- SERVER SIDE local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end local job = Player.PlayerData.job print('Job:', job.label) print('Grade:', job.grade.name) print('Level:', job.grade.level) print('On Duty:', job.onduty) print('Is Boss:', job.isboss) -- Check if specific job if job.name == 'police' then print('Player is police') end -- Check if specific grade or higher if job.name == 'police' and job.grade.level >= 3 then print('Player is high rank police (3+)') end ``` **Client-Side:** ```lua theme={null} -- CLIENT SIDE RegisterNetEvent('RSGCore:Client:OnPlayerLoaded', function() local PlayerData = RSGCore.Functions.GetPlayerData() if PlayerData.job.name == 'doctor' then -- Initialize doctor features TriggerEvent('doctor:client:init') end end) -- Listen for job changes RegisterNetEvent('RSGCore:Client:OnJobUpdate', function(job) print('New job:', job.label) print('New grade:', job.grade.name) end) ``` **Complete Example - Job Restricted Area:** ```lua theme={null} -- CLIENT SIDE CreateThread(function() local policeStation = vector3(2516.0, -1306.0, 48.0) while true do local PlayerData = RSGCore.Functions.GetPlayerData() local ped = PlayerPedId() local coords = GetEntityCoords(ped) local distance = #(coords - policeStation) if distance < 50.0 and PlayerData.job.name ~= 'police' then lib.notify({ description = 'Restricted area!', type = 'error' }) -- Teleport player away SetEntityCoords(ped, coords.x + 10, coords.y, coords.z) end Wait(5000) end end) ``` *** ## Gang System ### gang Structure ```lua theme={null} PlayerData.gang = { name = string, -- Gang name (e.g., 'lemoyne') label = string, -- Gang display name (e.g., 'Lemoyne Raiders') isboss = boolean, -- If player is gang leader grade = { name = string, -- Grade name level = number -- Grade level } } ``` ### Accessing Gang Info ```lua theme={null} -- SERVER SIDE local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end local gang = Player.PlayerData.gang if gang.name ~= 'none' then print('Player is in gang:', gang.label) print('Gang grade:', gang.grade.name) print('Is boss:', gang.isboss) else print('Player has no gang') end ``` *** ## Metadata ### metadata Structure Common metadata fields: ```lua theme={null} PlayerData.metadata = { hunger = number, -- 0-100 thirst = number, -- 0-100 cleanliness = number, -- 0-100 stress = number, -- 0-100 isdead = boolean, -- If player is dead inlaststand = boolean, -- If player is in last stand ishandcuffed = boolean, -- If player is handcuffed tracker = boolean, -- If player has tracker injail = number, -- Jail time remaining (0 = not in jail) jailitems = table, -- Items stored before jail status = table, -- Status effects phonedata = table, -- Phone settings callsign = string, -- Job callsign bloodtype = string, -- Blood type (A+, B-, etc.) dealerrep = number, -- Dealer reputation craftingrep = number, -- Crafting reputation attachmentcraftingrep = number, -- Attachment crafting reputation currentapartment = number,-- Current apartment ID jobrep = table, -- Job reputation rep = table -- General reputation } ``` ### Accessing Metadata **Server-Side:** ```lua theme={null} -- SERVER SIDE local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end -- Get specific metadata local hunger = Player.PlayerData.metadata.hunger local thirst = Player.PlayerData.metadata.thirst -- Check status if Player.PlayerData.metadata.isdead then print('Player is dead') end if Player.PlayerData.metadata.ishandcuffed then print('Player is handcuffed') end -- Set metadata Player.Functions.SetMetaData('hunger', 100) Player.Functions.SetMetaData('thirst', 100) ``` **Client-Side:** ```lua theme={null} -- CLIENT SIDE CreateThread(function() while true do local PlayerData = RSGCore.Functions.GetPlayerData() if PlayerData.metadata then -- Update HUD SendNUIMessage({ action = 'updateNeeds', hunger = PlayerData.metadata.hunger, thirst = PlayerData.metadata.thirst, cleanliness = PlayerData.metadata.cleanliness }) end Wait(5000) end end) ``` *** ## Inventory Items ### items Structure ```lua theme={null} PlayerData.items = { [1] = { name = string, -- Item name amount = number, -- Quantity info = table, -- Item metadata label = string, -- Display name description = string, -- Item description weight = number, -- Item weight type = string, -- 'item' or 'weapon' unique = boolean, -- If item is unique useable = boolean, -- If item can be used image = string, -- Image filename slot = number, -- Inventory slot shouldClose = boolean,-- If inventory should close on use combinable = table -- Crafting combinations }, -- More items... } ``` ### Accessing Inventory **Server-Side:** ```lua theme={null} -- SERVER SIDE local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end -- Get all items for slot, item in pairs(Player.PlayerData.items) do print('Slot', slot, ':', item.amount, 'x', item.label) end -- Check if has specific item local hasBread = exports['rsg-inventory']:HasItem(source, 'bread', 5) if hasBread then print('Player has at least 5 bread') end -- Get item count local breadCount = exports['rsg-inventory']:GetItemCount(source, 'bread') print('Player has', breadCount, 'bread') ``` **Client-Side:** ```lua theme={null} -- CLIENT SIDE local RSGCore = exports['rsg-core']:GetCoreObject() local PlayerData = RSGCore.Functions.GetPlayerData() for slot, item in pairs(PlayerData.items) do if item.name == 'weapon_revolver_cattleman' then print('Found revolver in slot', slot) print('Quality:', item.info.quality) print('Serial:', item.info.serie) end end ``` *** ## Position ### position Structure ```lua theme={null} PlayerData.position = { x = number, y = number, z = number } ``` ### Accessing Position ```lua theme={null} -- SERVER SIDE local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end local lastPos = Player.PlayerData.position print('Last saved position:', lastPos.x, lastPos.y, lastPos.z) -- Get current position local ped = GetPlayerPed(source) local currentPos = GetEntityCoords(ped) ``` *** ## Common Use Cases ### Use Case 1: Check Player Identity ```lua theme={null} -- SERVER SIDE RegisterNetEvent('bounty:server:checkBounty', function() local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end local citizenid = Player.PlayerData.citizenid local name = Player.PlayerData.charinfo.firstname .. ' ' .. Player.PlayerData.charinfo.lastname -- Check bounty in database MySQL.query('SELECT bounty FROM bounties WHERE citizenid = ?', {citizenid}, function(result) if result[1] then lib.notify(src, { description = name .. ' has a $' .. result[1].bounty .. ' bounty!', type = 'error' }) end end) end) ``` ### Use Case 2: Job Paycheck ```lua theme={null} -- SERVER SIDE CreateThread(function() while true do Wait(1800000) -- Every 30 minutes for src, Player in pairs(RSGCore.Players) do if Player then local job = Player.PlayerData.job if job.onduty and job.payment > 0 then Player.Functions.AddMoney('bank', job.payment, 'job-paycheck') lib.notify(src, { description = 'Paycheck received: $' .. job.payment, type = 'success' }) end end end end end) ``` ### Use Case 3: Metadata Status Effects ```lua theme={null} -- SERVER SIDE RegisterNetEvent('consumables:server:eatFood', function(itemSlot) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Remove item if exports['rsg-inventory']:RemoveItem(src, 'bread', 1, itemSlot, 'consumed') then -- Restore hunger local currentHunger = Player.PlayerData.metadata.hunger or 0 local newHunger = math.min(100, currentHunger + 25) Player.Functions.SetMetaData('hunger', newHunger) lib.notify(src, { description = 'You ate bread (+25 hunger)', type = 'success' }) end end) ``` *** ## Best Practices ### 1. Always Validate Player Exists ```lua theme={null} -- GOOD local Player = RSGCore.Functions.GetPlayer(source) if not Player then return end -- Now safe to use Player -- BAD local Player = RSGCore.Functions.GetPlayer(source) print(Player.PlayerData.citizenid) -- Can error! ``` ### 2. Use Player Functions for Money ```lua theme={null} -- GOOD - Uses built-in functions Player.Functions.AddMoney('cash', 100, 'reward') Player.Functions.RemoveMoney('cash', 50, 'purchase') -- BAD - Direct modification Player.PlayerData.money.cash = Player.PlayerData.money.cash + 100 ``` ### 3. Check Metadata Before Using ```lua theme={null} -- GOOD if Player.PlayerData.metadata and Player.PlayerData.metadata.hunger then local hunger = Player.PlayerData.metadata.hunger end -- BAD local hunger = Player.PlayerData.metadata.hunger -- Can error! ``` *** ## Summary | Data Type | Server Access | Client Access | Mutable | | ---------- | ----------------------------- | --------------------- | ----------- | | `charinfo` | `Player.PlayerData.charinfo` | `PlayerData.charinfo` | Rarely | | `money` | `Player.Functions.GetMoney()` | `PlayerData.money` | Server only | | `job` | `Player.PlayerData.job` | `PlayerData.job` | Server only | | `gang` | `Player.PlayerData.gang` | `PlayerData.gang` | Server only | | `metadata` | `Player.PlayerData.metadata` | `PlayerData.metadata` | Server only | | `items` | `Player.PlayerData.items` | `PlayerData.items` | Via exports | *** ## Next Steps * [Player Data Structure](/essentials/playerdata) - Complete PlayerData documentation * [Server Functions](/api-reference/endpoint/serverfunctionreference) - Player manipulation functions * [Inventory Functions](/inventory/functions) - Inventory management *** Need more help? Join the [RSG Framework Discord](https://discord.gg/rsg-redm-framework-914413479157448744)! # ๐Ÿ–ฅ๏ธ Server Events Source: https://rsg.mintlify.app/api-reference/endpoint/servereventreference Complete guide to RSG Core server-side events and event handlers ## Introduction Server events are the backbone of RSG Framework's server-side communication system. They allow resources to listen for and respond to player actions, system events, and cross-resource communication. Server events run on the server and can be triggered by clients using `TriggerServerEvent` or by other server-side code using `TriggerEvent`. *** ## How It Works ### Event Flow ``` Client Script โ†’ TriggerServerEvent('eventName', args) โ†’ Server Listens โ†’ Server Processes โ†’ Response ``` ### Registering Events Server events are registered using `RegisterNetEvent`: ```lua theme={null} -- SERVER SIDE RegisterNetEvent('eventName', function(arg1, arg2) local src = source -- The player who triggered the event -- Process event end) ``` Always validate data received from client events! Never trust client input. *** ## Core Player Events ### RSGCore:Server:OnPlayerLoaded Triggered when a player successfully loads into the server after character selection. ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:Server:OnPlayerLoaded', function() local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end print('Player loaded:', Player.PlayerData.charinfo.firstname) -- Your custom logic here -- Example: Give welcome bonus Player.Functions.AddMoney('cash', 100, 'welcome-bonus') end) ``` **Use Cases:** * Initialize player-specific data * Load custom player stats * Trigger welcome messages * Set up player blips/markers ### RSGCore:Server:OnPlayerUnload Triggered when a player logs out or returns to character selection. ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:Server:OnPlayerUnload', function() local src = source print('Player', src, 'logged out') -- Clean up player-specific data -- Remove from custom tables -- Save additional data if needed end) ``` **Use Cases:** * Clean up temporary data * Save custom player stats * Remove player from active lists * Stop player-specific threads *** ## Server Management Events ### RSGCore:Server:CloseServer Closes the server to non-whitelisted players with a custom reason. ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:Server:CloseServer', function(reason) local src = source -- Permission check if not RSGCore.Functions.HasPermission(src, 'admin') then RSGCore.Functions.Kick(src, 'You don\'t have permissions for this', nil, nil) return end reason = reason or 'Server maintenance' RSGCore.Config.Server.Closed = true RSGCore.Config.Server.ClosedReason = reason -- Kick all non-whitelisted players for playerId in pairs(RSGCore.Players) do if not RSGCore.Functions.HasPermission(playerId, RSGCore.Config.Server.WhitelistPermission) then RSGCore.Functions.Kick(playerId, reason, nil, nil) end end print('Server closed:', reason) end) ``` **Trigger from Client:** ```lua theme={null} -- CLIENT SIDE (admin only) TriggerServerEvent('RSGCore:Server:CloseServer', 'Emergency maintenance') ``` **Use Cases:** * Emergency maintenance * Scheduled restarts * Server events preparation * Testing with limited players ### RSGCore:Server:OpenServer Reopens the server to all players. ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:Server:OpenServer', function() local src = source if not RSGCore.Functions.HasPermission(src, 'admin') then RSGCore.Functions.Kick(src, 'You don\'t have permissions for this', nil, nil) return end RSGCore.Config.Server.Closed = false print('Server opened') end) ``` **Trigger from Client:** ```lua theme={null} -- CLIENT SIDE (admin only) TriggerServerEvent('RSGCore:Server:OpenServer') ``` *** ## Player Data Events ### RSGCore:UpdatePlayer Updates and saves player needs (hunger, thirst, cleanliness). ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:UpdatePlayer', function() local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Decrease player needs local newHunger = math.max(0, Player.PlayerData.metadata.hunger - RSGCore.Config.Player.HungerRate) local newThirst = math.max(0, Player.PlayerData.metadata.thirst - RSGCore.Config.Player.ThirstRate) local newCleanliness = math.max(0, Player.PlayerData.metadata.cleanliness - RSGCore.Config.Player.CleanlinessRate) -- Update metadata Player.Functions.SetMetaData('hunger', newHunger) Player.Functions.SetMetaData('thirst', newThirst) Player.Functions.SetMetaData('cleanliness', newCleanliness) -- Notify client TriggerClientEvent('hud:client:UpdateNeeds', src, newHunger, newThirst, newCleanliness) -- Save player data Player.Functions.Save() end) ``` This event is typically called on a timer to gradually decrease player needs over time. **Complete Example with Timer:** ```lua theme={null} -- SERVER SIDE CreateThread(function() while true do Wait(RSGCore.Config.Player.UpdateInterval or 300000) -- 5 minutes default for src, Player in pairs(RSGCore.Players) do if Player then TriggerEvent('RSGCore:UpdatePlayer', src) end end end end) ``` ### RSGCore:Server:SetMetaData Sets a specific metadata value for a player with validation. ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:Server:SetMetaData', function(meta, data) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Validate needs (cap at 100) if meta == 'hunger' or meta == 'thirst' or meta == 'cleanliness' then if data > 100 then data = 100 elseif data < 0 then data = 0 end end -- Update metadata Player.Functions.SetMetaData(meta, data) -- Update HUD TriggerClientEvent('hud:client:UpdateNeeds', src, Player.PlayerData.metadata.hunger, Player.PlayerData.metadata.thirst, Player.PlayerData.metadata.cleanliness ) end) ``` **Trigger from Client:** ```lua theme={null} -- CLIENT SIDE TriggerServerEvent('RSGCore:Server:SetMetaData', 'hunger', 75) ``` **Use Cases:** * Restore hunger after eating * Restore thirst after drinking * Restore cleanliness after bathing * Custom metadata updates *** ## Job & Duty Events ### RSGCore:ToggleDuty Toggles a player's on-duty status for their job. ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:ToggleDuty', function() local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Check if job has duty system if not Player.PlayerData.job.name then return end -- Toggle duty local newDutyStatus = not Player.PlayerData.job.onduty Player.Functions.SetJobDuty(newDutyStatus) -- Notify player lib.notify(src, { description = newDutyStatus and 'You are now on duty' or 'You are now off duty', type = 'info' }) -- Trigger client event for additional logic TriggerClientEvent('RSGCore:Client:SetDuty', src, newDutyStatus) end) ``` **Trigger from Client:** ```lua theme={null} -- CLIENT SIDE RegisterCommand('duty', function() TriggerServerEvent('RSGCore:ToggleDuty') end) ``` **Complete Example with Job Restrictions:** ```lua theme={null} -- SERVER SIDE local dutyJobs = { ['police'] = true, ['doctor'] = true, ['mechanic'] = true } RegisterNetEvent('RSGCore:ToggleDuty', function() local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Check if job has duty system if not dutyJobs[Player.PlayerData.job.name] then lib.notify(src, { description = 'Your job doesn\'t have a duty system', type = 'error' }) return end -- Toggle duty local newDutyStatus = not Player.PlayerData.job.onduty Player.Functions.SetJobDuty(newDutyStatus) -- Job-specific logic if Player.PlayerData.job.name == 'police' then if newDutyStatus then -- Add police blip TriggerClientEvent('police:client:addBlip', src) else -- Remove police blip TriggerClientEvent('police:client:removeBlip', src) end end lib.notify(src, { description = newDutyStatus and 'Clocked in' or 'Clocked out', type = 'success' }) end) ``` *** ## Callback Events ### RSGCore:Server:TriggerCallback Handles server-side callback requests from clients. ```lua theme={null} -- SERVER SIDE (internal - used by callback system) RegisterNetEvent('RSGCore:Server:TriggerCallback', function(name, ...) local src = source if not RSGCore.ServerCallbacks[name] then print('^1[ERROR]^7 Callback', name, 'does not exist') return end RSGCore.ServerCallbacks[name](src, function(...) TriggerClientEvent('RSGCore:Client:TriggerCallback', src, name, ...) end, ...) end) ``` This is an internal event used by the callback system. Use `RSGCore.Functions.CreateCallback` instead of listening to this event directly. **Proper Usage:** ```lua theme={null} -- SERVER SIDE - Create callback RSGCore.Functions.CreateCallback('myCallback', function(source, cb, arg1) local Player = RSGCore.Functions.GetPlayer(source) if not Player then cb(nil) return end cb(Player.PlayerData.money.cash) end) ``` ```lua theme={null} -- CLIENT SIDE - Trigger callback RSGCore.Functions.TriggerCallback('myCallback', function(cashAmount) print('Player has $' .. cashAmount) end, someArgument) ``` *** ## Permission Events ### RSGCore:Server:GivePermission Grants a permission level to a player (typically admin/god). ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:Server:GivePermission', function(targetId, permission) local src = source -- Only admins can grant permissions if not RSGCore.Functions.HasPermission(src, 'god') then lib.notify(src, { description = 'You don\'t have permission to do this', type = 'error' }) return end local Target = RSGCore.Functions.GetPlayer(targetId) if not Target then lib.notify(src, { description = 'Player not found', type = 'error' }) return end -- Grant permission RSGCore.Functions.AddPermission(targetId, permission) lib.notify(src, { description = 'Granted ' .. permission .. ' to player', type = 'success' }) lib.notify(targetId, { description = 'You have been granted ' .. permission .. ' permissions', type = 'info' }) end) ``` ### RSGCore:Server:RemovePermission Removes a permission level from a player. ```lua theme={null} -- SERVER SIDE RegisterNetEvent('RSGCore:Server:RemovePermission', function(targetId, permission) local src = source if not RSGCore.Functions.HasPermission(src, 'god') then lib.notify(src, { description = 'You don\'t have permission to do this', type = 'error' }) return end -- Remove permission RSGCore.Functions.RemovePermission(targetId, permission) lib.notify(src, { description = 'Removed ' .. permission .. ' from player', type = 'success' }) end) ``` *** ## Best Practices ### 1. Always Validate Player ```lua theme={null} -- GOOD RegisterNetEvent('myEvent', function(arg) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Safe to use Player end) -- BAD RegisterNetEvent('myEvent', function(arg) local src = source local Player = RSGCore.Functions.GetPlayer(src) -- No check - will error if player doesn't exist! Player.Functions.AddMoney('cash', 100) end) ``` ### 2. Validate Client Input ```lua theme={null} -- GOOD RegisterNetEvent('shop:purchase', function(itemName, amount) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Validate item exists if not RSGCore.Shared.Items[itemName] then return end -- Validate amount if type(amount) ~= 'number' or amount < 1 or amount > 100 then return end -- Process purchase end) ``` ### 3. Use Meaningful Event Names ```lua theme={null} -- GOOD RegisterNetEvent('banking:server:deposit', ...) RegisterNetEvent('inventory:server:giveItem', ...) RegisterNetEvent('police:server:handcuff', ...) -- BAD RegisterNetEvent('doStuff', ...) RegisterNetEvent('event1', ...) RegisterNetEvent('handle', ...) ``` ### 4. Handle Permissions Properly ```lua theme={null} -- GOOD RegisterNetEvent('admin:giveWeapon', function(targetId, weapon) local src = source if not RSGCore.Functions.HasPermission(src, 'admin') then return -- Silent fail or notify end -- Admin action end) ``` *** ## Common Patterns ### Pattern 1: Transaction Event ```lua theme={null} RegisterNetEvent('banking:server:deposit', function(amount) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Validate amount if type(amount) ~= 'number' or amount < 1 then lib.notify(src, {description = 'Invalid amount', type = 'error'}) return end -- Check player has cash if Player.Functions.GetMoney('cash') < amount then lib.notify(src, {description = 'Not enough cash', type = 'error'}) return end -- Process deposit Player.Functions.RemoveMoney('cash', amount, 'bank-deposit') Player.Functions.AddMoney('bank', amount, 'bank-deposit') lib.notify(src, { description = 'Deposited $' .. amount, type = 'success' }) end) ``` ### Pattern 2: Item Give/Take Event ```lua theme={null} RegisterNetEvent('admin:giveItem', function(targetId, itemName, amount) local src = source -- Permission check if not RSGCore.Functions.HasPermission(src, 'admin') then return end -- Validate inputs local Target = RSGCore.Functions.GetPlayer(targetId) if not Target then return end if not RSGCore.Shared.Items[itemName] then return end amount = tonumber(amount) or 1 -- Give item exports['rsg-inventory']:AddItem(targetId, itemName, amount, nil, nil, 'admin-give') lib.notify(src, { description = 'Gave item to player', type = 'success' }) end) ``` ### Pattern 3: Proximity Check Event ```lua theme={null} RegisterNetEvent('shop:server:purchase', function(shopId, itemName) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then return end -- Get shop location local shopCoords = Config.Shops[shopId].coords -- Check if player is near local ped = GetPlayerPed(src) local playerCoords = GetEntityCoords(ped) local distance = #(playerCoords - shopCoords) if distance > 5.0 then lib.notify(src, {description = 'Too far from shop', type = 'error'}) return end -- Process purchase end) ``` *** ## Troubleshooting ### Event Not Triggering Make sure the event name matches exactly between client and server Use `RegisterNetEvent` for networked events triggered across client/server Always validate `source` exists before using it ### Player Not Found ```lua theme={null} -- Common issue RegisterNetEvent('myEvent', function() local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then print('Player not loaded yet or disconnected') return end end) ``` ### Permission Denied ```lua theme={null} -- Always check permissions if not RSGCore.Functions.HasPermission(src, 'admin') then print('Player', src, 'tried to use admin command') return end ``` *** ## Summary | Event | Purpose | Permission Required | | --------------------------------- | ------------------- | ------------------- | | `RSGCore:Server:OnPlayerLoaded` | Player login | None | | `RSGCore:Server:OnPlayerUnload` | Player logout | None | | `RSGCore:Server:CloseServer` | Close server | Admin | | `RSGCore:Server:OpenServer` | Open server | Admin | | `RSGCore:UpdatePlayer` | Update needs | None | | `RSGCore:Server:SetMetaData` | Set player metadata | None | | `RSGCore:ToggleDuty` | Toggle job duty | None | | `RSGCore:Server:GivePermission` | Grant permissions | God | | `RSGCore:Server:RemovePermission` | Remove permissions | God | *** ## Next Steps * [Client Events](/api-reference/endpoint/clienteventreference) - Client-side event reference * [Server Functions](/api-reference/endpoint/serverfunctionreference) - Server function reference * [Callbacks](/essentials/callbacks) - Learn about the callback system *** Need more help? Join the [RSG Framework Discord](https://discord.gg/rsg-redm-framework-914413479157448744)! # ๐Ÿ–ฅ๏ธ Server Function Reference Source: https://rsg.mintlify.app/api-reference/endpoint/serverfunctionreference Learn about and how to use common core server functions! ### RSGCore.Functions.GetCoords * Get the coords of a passed entity ```lua theme={null} ---@param entity number ---@return vector4 function RSGCore.Functions.GetCoords(entity) local coords = GetEntityCoords(entity, false) local heading = GetEntityHeading(entity) return vector4(coords.x, coords.y, coords.z, heading) end -- Example local ped = GetPlayerPed(source) local coords = RSGCore.Functions.GetCoords(ped) print(coords) ``` ### RSGCore.Functions.GetIdentifier * Get the identifier of a passed entity ```lua theme={null} ---@param source any ---@param idtype string ---@return string? function RSGCore.Functions.GetIdentifier(source, idtype) return GetPlayerIdentifierByType(source, idtype or 'license') end -- Example local identifier = RSGCore.Functions.GetIdentifier(source, 'license') print(identifier) OR -- defaults to the identifier in the config of rsg-core local identifier = RSGCore.Functions.GetIdentifier(source) print(identifier) ``` ### RSGCore.Functions.GetSource * Gets a players server id (source). Returns 0 if no player is found. ```lua theme={null} ---@param identifier string ---@return number function RSGCore.Functions.GetSource(identifier) for src, _ in pairs(RSGCore.Players) do local idens = GetPlayerIdentifiers(src) for _, id in pairs(idens) do if identifier == id then return src end end end return 0 end -- Example local identifier = RSGCore.Functions.GetIdentifier(source, 'license') local playerSource = RSGCore.Functions.GetSource(identifier) print(playerSource) ``` ### RSGCore.Functions.GetPlayer * Get player with given server id (source) ```lua theme={null} ---@param source any ---@return table function RSGCore.Functions.GetPlayer(source) if type(source) == 'number' then return RSGCore.Players[source] else return RSGCore.Players[RSGCore.Functions.GetSource(source)] end end -- Example local Player = RSGCore.Functions.GetPlayer(source) print(RSGCore.Debug(Player)) OR -- access some player data local Player = RSGCore.Functions.GetPlayer(source) print(Player.PlayerData.citizenid) ``` ### RSGCore.Functions.GetPlayerByCitizenId * Get player by citizen id ```lua theme={null} ---@param citizenid string ---@return table? function RSGCore.Functions.GetPlayerByCitizenId(citizenid) for src in pairs(RSGCore.Players) do if RSGCore.Players[src].PlayerData.citizenid == citizenid then return RSGCore.Players[src] end end return nil end -- Example local Player = RSGCore.Functions.GetPlayerByCitizenId('ONZ55343') print(RSGCore.Debug(Player)) OR -- access some player data local Player = RSGCore.Functions.GetPlayerByCitizenId('ONZ55343') print(Player.PlayerData.license) ``` ### RSGCore.Functions.GetPlayers * Get all players. Returns the server ids of all players. ```lua theme={null} ---@return table function RSGCore.Functions.GetPlayers() local sources = {} for k in pairs(RSGCore.Players) do sources[#sources + 1] = k end return sources end -- Example local Players = RSGCore.Functions.GetPlayers() print(RSGCore.Debug(Players)) ``` ### RSGCore.Functions.GetRSGPlayers * Will return an array of RSG Player class instances unlike the GetPlayers() wrapper which only returns IDs ```lua theme={null} ---@return table function RSGCore.Functions.GetRSGPlayers() return RSGCore.Players end -- Example local Players = RSGCore.Functions.GetRSGPlayers() print(RSGCore.Debug(Players)) ``` ### RSGCore.Functions.CreateCallBack * Create Server Callback. ```lua theme={null} ---@param name string ---@param cb function function RSGCore.Functions.CreateCallback(name, cb) RSGCore.ServerCallbacks[name] = cb end -- Example RSGCore.Functions.CreateCallback('callbackName', function(source, cb) cb('Ok') end) ``` ### RSGCore.Functions.CreateUseableItem * Create a usable item ```lua theme={null} ---@param item string ---@param data function function RSGCore.Functions.CreateUseableItem(item, data) RSGCore.UsableItems[item] = data end -- Example RSGCore.Functions.CreateUseableItem('my_cool_item', function(source, item) local Player = RSGCore.Functions.GetPlayer(source) if not Player.Functions.GetItemByName(item.name) then return end -- Trigger code here for what item should do end) ``` ### RSGCore.Functions.CanUseItem * Check if a player can use an item ```lua theme={null} ---@param item string ---@return any function RSGCore.Functions.CanUseItem(item) return RSGCore.UsableItems[item] end -- Example local canUse = RSGCore.Functions.CanUseItem('my_cool_item') print(canUse) OR local canUse = RSGCore.Functions.CanUseItem('my_cool_item') if not canUse then return end -- Trigger code here ``` ### RSGCore.Functions.UseItem * Use an item ```lua theme={null} ---@param source any ---@param item string function RSGCore.Functions.UseItem(source, item) if GetResourceState('rsg-inventory') == 'missing' then return end exports['rsg-inventory']:UseItem(source, item) end -- Example local Player = RSGCore.Functions.GetPlayer(source) if not Player.Functions.GetItemByName('my_cool_item') then return end RSGCore.Functions.UseItem(source, 'my_cool_item') ``` ### RSGCore.Functions.GetOfflinePlayerByCitizenId * Get offline player data by citizen id (pulls from database) ```lua theme={null} ---@param citizenid string ---@return table? function RSGCore.Functions.GetOfflinePlayerByCitizenId(citizenid) return RSGCore.Player.GetOfflinePlayer(citizenid) end -- Example local OfflinePlayer = RSGCore.Functions.GetOfflinePlayerByCitizenId('ABC12345') if OfflinePlayer then print(OfflinePlayer.PlayerData.charinfo.firstname) end ``` ### RSGCore.Functions.GetPlayerByLicense * Get player by license (checks online players first, then database) ```lua theme={null} ---@param license string ---@return table? function RSGCore.Functions.GetPlayerByLicense(license) return RSGCore.Player.GetPlayerByLicense(license) end -- Example local license = 'license:1234567890abcdef' local Player = RSGCore.Functions.GetPlayerByLicense(license) if Player then print(Player.PlayerData.name) end ``` ### RSGCore.Functions.GetPlayerByAccount * Get player by account number ```lua theme={null} ---@param account string ---@return table? function RSGCore.Functions.GetPlayerByAccount(account) for src in pairs(RSGCore.Players) do if RSGCore.Players[src].PlayerData.charinfo.account == account then return RSGCore.Players[src] end end return nil end -- Example local Player = RSGCore.Functions.GetPlayerByAccount('US04RSG1234567890') if Player then print(Player.PlayerData.citizenid) end ``` ### RSGCore.Functions.GetPlayerByCharInfo * Get player by any character info property ```lua theme={null} ---@param property string ---@param value string ---@return table? function RSGCore.Functions.GetPlayerByCharInfo(property, value) for src in pairs(RSGCore.Players) do local charinfo = RSGCore.Players[src].PlayerData.charinfo if charinfo[property] ~= nil and charinfo[property] == value then return RSGCore.Players[src] end end return nil end -- Example -- Find player by first name local Player = RSGCore.Functions.GetPlayerByCharInfo('firstname', 'John') if Player then print(Player.PlayerData.charinfo.lastname) end ``` ### RSGCore.Functions.GetPlayersOnDuty * Get all players on duty for a specific job ```lua theme={null} ---@param job string ---@return table, number function RSGCore.Functions.GetPlayersOnDuty(job) local players = {} local count = 0 for src, Player in pairs(RSGCore.Players) do if Player.PlayerData.job.name == job then if Player.PlayerData.job.onduty then players[#players + 1] = src count += 1 end end end return players, count end -- Example local cops, copCount = RSGCore.Functions.GetPlayersOnDuty('vallaw') print('There are '.. copCount ..' cops on duty') for i = 1, #cops do print('Cop source: '.. cops[i]) end ``` ### RSGCore.Functions.GetDutyCount * Get the count of players on duty for a specific job ```lua theme={null} ---@param job string ---@return number function RSGCore.Functions.GetDutyCount(job) local count = 0 for _, Player in pairs(RSGCore.Players) do if Player.PlayerData.job.name == job then if Player.PlayerData.job.onduty then count += 1 end end end return count end -- Example local copCount = RSGCore.Functions.GetDutyCount('vallaw') if copCount < 2 then print('Not enough cops online!') end ``` ### RSGCore.Functions.GetClosestPlayer * Get the closest player to a source player or coordinates ```lua theme={null} ---@param source number ---@param coords vector ---@return number, number function RSGCore.Functions.GetClosestPlayer(source, coords) -- Returns closestPlayer (server id), closestDistance end -- Example local closestPlayer, distance = RSGCore.Functions.GetClosestPlayer(source) if closestPlayer ~= -1 and distance < 3.0 then print('Player '.. closestPlayer ..' is '.. distance ..' units away') end ``` ### RSGCore.Functions.SetPlayerBucket * Set a player's routing bucket (for instancing) ```lua theme={null} ---@param source any ---@param bucket any ---@return boolean function RSGCore.Functions.SetPlayerBucket(source, bucket) if source and bucket then local plicense = RSGCore.Functions.GetIdentifier(source, 'license') Player(source).state:set('instance', bucket, true) SetPlayerRoutingBucket(source, bucket) RSGCore.Player_Buckets[plicense] = { id = source, bucket = bucket } return true else return false end end -- Example -- Put player in their own instance (bucket 1) RSGCore.Functions.SetPlayerBucket(source, 1) ``` ### RSGCore.Functions.SetEntityBucket * Set an entity's routing bucket ```lua theme={null} ---@param entity number ---@param bucket number ---@return boolean function RSGCore.Functions.SetEntityBucket(entity, bucket) if entity and bucket then SetEntityRoutingBucket(entity, bucket) RSGCore.Entity_Buckets[entity] = { id = entity, bucket = bucket } return true else return false end end -- Example local vehicle = GetVehiclePedIsIn(GetPlayerPed(source)) RSGCore.Functions.SetEntityBucket(vehicle, 1) ``` ### RSGCore.Functions.GetPlayersInBucket * Get all players in a specific routing bucket ```lua theme={null} ---@param bucket number ---@return table|boolean function RSGCore.Functions.GetPlayersInBucket(bucket) local curr_bucket_pool = {} if RSGCore.Player_Buckets and next(RSGCore.Player_Buckets) then for _, v in pairs(RSGCore.Player_Buckets) do if v.bucket == bucket then curr_bucket_pool[#curr_bucket_pool + 1] = v.id end end return curr_bucket_pool else return false end end -- Example local playersInBucket = RSGCore.Functions.GetPlayersInBucket(1) if playersInBucket then for i = 1, #playersInBucket do print('Player in bucket: '.. playersInBucket[i]) end end ``` ### RSGCore.Functions.SpawnVehicle * Server-side vehicle spawning ```lua theme={null} ---@param source any ---@param model any ---@param coords vector ---@param warp boolean ---@return number function RSGCore.Functions.SpawnVehicle(source, model, coords, warp) -- Spawns vehicle and returns vehicle handle end -- Example local coords = GetEntityCoords(GetPlayerPed(source)) local veh = RSGCore.Functions.SpawnVehicle(source, 'CART01', coords, true) print('Spawned vehicle: '.. veh) ``` ### RSGCore.Functions.Kick * Kick a player from the server ```lua theme={null} ---@param source any ---@param reason string ---@param setKickReason boolean ---@param deferrals boolean function RSGCore.Functions.Kick(source, reason, setKickReason, deferrals) reason = '\n' .. reason .. '\n๐Ÿ”ธ Check our Discord for further information: ' .. RSGCore.Config.Server.Discord -- Handles the kick with retries end -- Example RSGCore.Functions.Kick(source, 'You have been kicked for: Cheating', false, false) ``` ### RSGCore.Functions.IsWhitelisted * Check if a player is whitelisted ```lua theme={null} ---@param source any ---@return boolean function RSGCore.Functions.IsWhitelisted(source) if not RSGCore.Config.Server.Whitelist then return true end if RSGCore.Functions.HasPermission(source, RSGCore.Config.Server.WhitelistPermission) then return true end return false end -- Example if not RSGCore.Functions.IsWhitelisted(source) then RSGCore.Functions.Kick(source, 'You are not whitelisted', false, false) end ``` ### RSGCore.Functions.AddPermission * Add a permission to a player ```lua theme={null} ---@param source any ---@param permission string function RSGCore.Functions.AddPermission(source, permission) if not IsPlayerAceAllowed(source, permission) then ExecuteCommand(('add_principal player.%s rsgcore.%s'):format(source, permission)) RSGCore.Commands.Refresh(source) end end -- Example RSGCore.Functions.AddPermission(source, 'admin') ``` ### RSGCore.Functions.RemovePermission * Remove a permission from a player ```lua theme={null} ---@param source any ---@param permission string function RSGCore.Functions.RemovePermission(source, permission) if permission then if IsPlayerAceAllowed(source, permission) then ExecuteCommand(('remove_principal player.%s rsgcore.%s'):format(source, permission)) RSGCore.Commands.Refresh(source) end end end -- Example RSGCore.Functions.RemovePermission(source, 'admin') ``` ### RSGCore.Functions.HasPermission * Check if a player has a specific permission ```lua theme={null} ---@param source any ---@param permission string|table ---@return boolean function RSGCore.Functions.HasPermission(source, permission) if type(permission) == 'string' then if IsPlayerAceAllowed(source, permission) then return true end elseif type(permission) == 'table' then for _, permLevel in pairs(permission) do if IsPlayerAceAllowed(source, permLevel) then return true end end end return false end -- Example if RSGCore.Functions.HasPermission(source, 'admin') then print('Player is an admin') end -- Check multiple permissions if RSGCore.Functions.HasPermission(source, {'admin', 'mod'}) then print('Player is admin or mod') end ``` ### RSGCore.Functions.GetPermission * Get all permissions for a player ```lua theme={null} ---@param source any ---@return table function RSGCore.Functions.GetPermission(source) local perms = {} for _, v in pairs(RSGCore.Config.Server.Permissions) do if IsPlayerAceAllowed(src, v) then perms[v] = true end end return perms end -- Example local perms = RSGCore.Functions.GetPermission(source) for perm, enabled in pairs(perms) do print(perm .. ': ' .. tostring(enabled)) end ``` ### RSGCore.Functions.IsPlayerBanned * Check if a player is banned ```lua theme={null} ---@param source any ---@return boolean, string? function RSGCore.Functions.IsPlayerBanned(source) local plicense = RSGCore.Functions.GetIdentifier(source, 'license') local result = MySQL.single.await('SELECT id, reason, expire FROM bans WHERE license = ?', { plicense }) if not result then return false end if os.time() < result.expire then -- Returns true and ban message return true, 'Ban message here...' else MySQL.query('DELETE FROM bans WHERE id = ?', { result.id }) end return false end -- Example local isBanned, reason = RSGCore.Functions.IsPlayerBanned(source) if isBanned then RSGCore.Functions.Kick(source, reason, false, false) end ``` ### RSGCore.Functions.IsLicenseInUse * Check if a license is currently in use (duplicate check) ```lua theme={null} ---@param license any ---@return boolean function RSGCore.Functions.IsLicenseInUse(license) local players = GetPlayers() for _, player in pairs(players) do local playerLicense = RSGCore.Functions.GetIdentifier(player, 'license') if playerLicense == license then return true end end return false end -- Example if RSGCore.Functions.IsLicenseInUse(license) then print('This license is already connected') end ``` # ๐Ÿค“ Development Guides Source: https://rsg.mintlify.app/development Learn how to write optimized code! ## General Practices * **Localize as many functions and variables as possible. Lua can read them faster** ```lua theme={null} myVariable = false -- Don't use this local myVariable = false -- Use this function someFunction() -- Don't use this print('Im a global function!') end local function someFunction() -- Use this print('Im a local function!') end ``` * **Instead of using `table.insert` use `tableName[#tableName+1] = data`** ```lua theme={null} function someFunction() local table = {} table.insert(table, {}) -- Don't use this table[#table+1] = {} -- Use this end ``` * **Instead of using `if something ~= nil` use `if something then`. This method checks for nil and/or false at the same time** ```lua theme={null} function someFunction() local bool = nil if bool ~= nil then -- Don't use this print('bool was not nil but also could be false!') end if bool then -- Use this print('bool was neither nil or false!') end end ``` * **If you are creating a function or an event, make it so that it can be used in different scenarios with different variables. Keep it universal basically** ```lua theme={null} local function someFunction(param1, param2, param3) print('Im a function that accepts 3 parameters which allows for multiple conditions!') if param1 == 'something' then print('I met condition number one!') elseif param2 == 'somethingelse' then print('I met condition number two!') elseif param3 == 'somethingelsemore' then print('I met condition number three!') end end RegisterNetEvent('someEvent', function(param1, param2, param3) print('Im an event that accepts 3 parameters which allows for multiple conditions!') if param1 == 'something' then print('I met condition number one!') elseif param2 == 'somethingelse' then print('I met condition number two!') elseif param3 == 'somethingelsemore' then print('I met condition number three!') end end) ``` * **When writing code use what's known as "short returns" for failed conditions** ```lua theme={null} local function someFunction(param1, param2, param3) if not param1 then return end print('I met condition number one!') if not param2 then return end print('I met condition number two!') if not param3 then return end print('I met condition number three!') end ``` ## Native Usage * **Always replace `GetPlayerPed(-1)` with `PlayerPedId()`** ```lua theme={null} local function someFunction() local ped = GetPlayerPed(-1) -- Don't use this local ped = PlayerPedId() -- Use this end ``` * **Always replace `GetDistanceBetweenCoords` with lua math aka `#(vector3 - vector3)`** ```lua theme={null} local function someFunction() local ped = PlayerPedId() local pCoords = GetEntityCoords(ped) local coords = vector3(-29.53, -1103.67, 26.42) local dist = GetDistanceBetweenCoords(pCoords, coords, true) -- Don't use this local dist = #(pCoords - coords) -- Use this if dist < 5 then print('Im within 5 distance units of the coords!') end end ``` ### Native Research Sites/Tools * [RedM Native Reference](https://rdr3natives.com/) * [Natives | RedLookup](https://redlookup.com/natives?v=2\&p=1\&pp=50) * [femga/rdr3\_discoveries: Some interesting things from Red Dead Redemption 2.](https://github.com/femga/rdr3_discoveries) * [Halen84/RDR3-Native-Flags-And-Enums: Contains flags and enums for natives](https://github.com/Halen84/RDR3-Native-Flags-And-Enums) ## Loops * **Control your while loops and when they run** ```lua theme={null} local function exampleLoop() CreateThread(function() while listen do print('running while loop only when needed') Wait(1) end end) end local listen = false CreateThread(function() LoopZone = CircleZone:Create(vector3(-851.63, 74.36, 51.86), 5.0, { name = "ExampleLoop", debugPoly = true, }) LoopZone:onPlayerInOut(function(isPointInside) if isPointInside then listen = true exampleLoop() -- Initiate loop else listen = false -- turns off when your outside the zone end end) end) ``` * **If you do have to create a thread that includes a "while" loop, always avoid using "while true do" if able. If you have to use this, follow the next tip, and it wonโ€™t impact performance as much** * **Control your thread times by using a variable that changes the wait time retroactively. So, you can set the thread wait time to say 1000ms which checks for your if statement every second and if it makes it into the statement, you can lower the wait time by just changing the variable value. Wait(sleep)** ```lua theme={null} CreateThread(function() while true do Wait(1) inRange = false local pos = GetEntityCoords(PlayerPedId()) if #(pos - vector3(-829.11, 75.03, 52.73)) < 10.0 then inRange = true print('Im in range and the loop runs faster') else print('Im not in range so i run only onces every 2.5 seconds') end if not inRange then Wait(2500) end end end) ``` * **If you have job specific loops, make sure they only apply to players with that job. There's no reason for someone who is not a cop to be running a loop on their machine that does not apply to them** ```lua theme={null} local function exampleJobLoop() local job = RSGCore.Functions.GetPlayerData().job.name CreateThread(function() while job == 'law' do print('im a lawman!') Wait(1) end end) end ``` ## Security * A surplus amount of security in a code is not a bad thing. Don't be afraid to add in multiple if checks or create random variables to pass through your events * Never do any type of transaction with the player regarding money or items on the client side of a resource ## Event Handlers * **When setting variables inside your resource, handlers come in especially handy due to not needing to constantly run checks** ```lua theme={null} -- These are client-side examples local isLoggedIn = false local PlayerData = {} AddStateBagChangeHandler('isLoggedIn', nil, function(_, _, value) -- FiveM native method if value then isLoggedIn = true PlayerData = RSGCore.Functions.GetPlayerData() else isLoggedIn = false PlayerData = {} end end) AddEventHandler('RSGCore:Client:OnPlayerLoaded', function() -- Don't use this with the native method isLoggedIn = true PlayerData = RSGCore.Functions.GetPlayerData() end) RegisterNetEvent('RSGCore:Client:OnPlayerUnload', function() -- Don't use this with the native method isLoggedIn = false PlayerData = {} end) RegisterNetEvent('RSGCore:Player:SetPlayerData', function(val) PlayerData = val end) ``` # ๐Ÿ”„ Callbacks Guide Source: https://rsg.mintlify.app/essentials/callbacks Learn how to use RSG Core's callback system for client-server communication ## Introduction Callbacks in RSG Core provide a way to request data from the server and wait for a response, or vice versa. They're essential for synchronous communication between client and server scripts. **Location**: `resources/[framework]/rsg-core/server/functions.lua` & `client/functions.lua` Callbacks are perfect for situations where you need to wait for data before continuing execution, like checking if a player has an item, getting database information, or validating actions. *** ## Core Features ### ๐Ÿ“ก Bidirectional Communication * **Server Callbacks**: Client requests data from server * **Client Callbacks**: Server requests data from specific client * **Multiple Arguments**: Pass any number of arguments * **Any Data Types**: Return tables, strings, numbers, booleans ### ๐Ÿ”’ Secure by Design * **Server-side Validation**: All sensitive logic stays on server * **No Client Trust**: Client only receives processed results * **Source Tracking**: Always know which player triggered callback ### โšก Efficient Data Flow * **Async Processing**: Non-blocking operations * **Promise Support**: Await pattern for cleaner code * **No Event Spam**: Request-response pattern prevents loops *** ## Server Callbacks Server callbacks allow you to request data from the server and wait for the response on the client. ### Creating a Server Callback Use `RSGCore.Functions.CreateCallback` on the **server** to create a callback: ```lua theme={null} -- SERVER SIDE (server/main.lua or your resource's server file) RSGCore.Functions.CreateCallback('rsg-example:server:getData', function(source, cb, arg1, arg2) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then cb(nil) return end -- Do your server-side logic local data = { name = Player.PlayerData.charinfo.firstname .. ' ' .. Player.PlayerData.charinfo.lastname, job = Player.PlayerData.job.label, money = Player.PlayerData.money.cash, customArg1 = arg1, customArg2 = arg2 } -- Send data back to client cb(data) end) ``` **Parameters**: * `source`: The player who triggered the callback * `cb`: The callback function to send data back * `...`: Any additional arguments passed from the client ### Triggering a Server Callback Use `RSGCore.Functions.TriggerCallback` on the **client** to call the callback: ```lua theme={null} -- CLIENT SIDE (client/main.lua or your resource's client file) RSGCore.Functions.TriggerCallback('rsg-example:server:getData', function(data) if data then print('Player Name: ' .. data.name) print('Job: ' .. data.job) print('Cash: $' .. data.money) else print('No data received') end end, 'argument1', 'argument2') ``` *** ## Client Callbacks Client callbacks allow the server to request data from a specific client and wait for the response. ### Creating a Client Callback Use `RSGCore.Functions.CreateClientCallback` on the **client** to create a callback: ```lua theme={null} -- CLIENT SIDE RSGCore.Functions.CreateClientCallback('rsg-example:client:getVehicleData', function(cb) local ped = PlayerPedId() local vehicle = GetVehiclePedIsIn(ped, false) if vehicle ~= 0 then local data = { model = GetEntityModel(vehicle), plate = GetVehicleNumberPlateText(vehicle), health = GetVehicleEngineHealth(vehicle), coords = GetEntityCoords(vehicle) } cb(data) else cb(nil) -- Player not in a vehicle end end) ``` ### Triggering a Client Callback Use `RSGCore.Functions.TriggerClientCallback` on the **server** to call the callback: ```lua theme={null} -- SERVER SIDE RSGCore.Functions.TriggerClientCallback('rsg-example:client:getVehicleData', source, function(data) if data then print('Vehicle Model: ' .. data.model) print('Plate: ' .. data.plate) print('Engine Health: ' .. data.health) else print('Player is not in a vehicle') end end) ``` *** ## Practical Examples ### Example 1: Checking if Player Has Item **Server Callback**: ```lua theme={null} -- SERVER RSGCore.Functions.CreateCallback('rsg-shop:server:hasEnoughMoney', function(source, cb, amount) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then cb(false) return end if Player.Functions.GetMoney('cash') >= amount then cb(true) else cb(false) end end) ``` **Client Usage**: ```lua theme={null} -- CLIENT local price = 50 RSGCore.Functions.TriggerCallback('rsg-shop:server:hasEnoughMoney', function(hasEnough) if hasEnough then print('You have enough money!') -- Proceed with purchase else print('You don\'t have enough money!') end end, price) ``` ### Example 2: Getting Player's Horses **Server Callback with Database**: ```lua theme={null} -- SERVER RSGCore.Functions.CreateCallback('rsg-horses:server:getOwnedHorses', function(source, cb) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then cb({}) return end local result = MySQL.query.await('SELECT * FROM player_horses WHERE citizenid = ?', { Player.PlayerData.citizenid }) if result and result[1] then cb(result) else cb({}) end end) ``` **Client Usage**: ```lua theme={null} -- CLIENT RSGCore.Functions.TriggerCallback('rsg-horses:server:getOwnedHorses', function(horses) if #horses > 0 then print('You own ' .. #horses .. ' horses:') for i = 1, #horses do print(' - ' .. horses[i].name) end else print('You don\'t own any horses') end end) ``` ### Example 3: Purchasing Item **Server Callback**: ```lua theme={null} -- SERVER RSGCore.Functions.CreateCallback('rsg-shop:server:purchaseItem', function(source, cb, itemName, amount, price) local src = source local Player = RSGCore.Functions.GetPlayer(src) if not Player then cb({ success = false, message = 'Player not found' }) return end local totalPrice = price * amount -- Check if player has enough money if Player.Functions.GetMoney('cash') < totalPrice then cb({ success = false, message = 'Not enough money' }) return end -- Check if player has inventory space if not exports['rsg-inventory']:CanAddItem(src, itemName, amount) then cb({ success = false, message = 'Not enough inventory space' }) return end -- Remove money if not Player.Functions.RemoveMoney('cash', totalPrice, 'shop-purchase') then cb({ success = false, message = 'Failed to remove money' }) return end -- Add item if exports['rsg-inventory']:AddItem(src, itemName, amount, nil, nil, 'shop-purchase') then cb({ success = true, message = 'Purchase successful' }) else -- Refund money if item add fails Player.Functions.AddMoney('cash', totalPrice, 'shop-refund') cb({ success = false, message = 'Failed to add item' }) end end) ``` **Client Usage**: ```lua theme={null} -- CLIENT local itemName = 'bread' local amount = 3 local pricePerUnit = 5 RSGCore.Functions.TriggerCallback('rsg-shop:server:purchaseItem', function(result) if result.success then lib.notify({ title = 'Shop', description = result.message, type = 'success' }) else lib.notify({ title = 'Shop', description = result.message, type = 'error' }) end end, itemName, amount, pricePerUnit) ``` ### Example 4: Client Callback for Coordinates **Client Callback**: ```lua theme={null} -- CLIENT RSGCore.Functions.CreateClientCallback('rsg-admin:client:getPlayerCoords', function(cb) local ped = PlayerPedId() local coords = GetEntityCoords(ped) local heading = GetEntityHeading(ped) cb({ x = coords.x, y = coords.y, z = coords.z, heading = heading }) end) ``` **Server Usage**: ```lua theme={null} -- SERVER RegisterCommand('getcoords', function(source, args) local src = source if not RSGCore.Functions.HasPermission(src, 'admin') then return end RSGCore.Functions.TriggerClientCallback('rsg-admin:client:getPlayerCoords', src, function(coords) if coords then print(('Player coords: x=%.2f, y=%.2f, z=%.2f, heading=%.2f'):format( coords.x, coords.y, coords.z, coords.heading )) end end) end) ``` *** ## Best Practices **Use Descriptive Names**: Name your callbacks clearly to indicate what they do * Good: `'rsg-shop:server:purchaseItem'` * Bad: `'shop:buy'` **Always Validate Data**: Never trust client-sent data without validation ```lua theme={null} -- BAD RSGCore.Functions.CreateCallback('example', function(source, cb, amount) Player.Functions.AddMoney('cash', amount) -- NO VALIDATION! end) -- GOOD RSGCore.Functions.CreateCallback('example', function(source, cb, amount) if type(amount) ~= 'number' or amount <= 0 or amount > 1000 then cb(false) return end Player.Functions.AddMoney('cash', amount) cb(true) end) ``` **Always Provide Fallbacks**: Handle cases where data might be nil ```lua theme={null} RSGCore.Functions.TriggerCallback('example:getData', function(data) if not data then print('Failed to get data') return end -- Use data end) ``` ### Performance Tips 1. **Don't spam callbacks**: Avoid calling callbacks in loops or every frame 2. **Cache results**: If data doesn't change often, cache it instead of calling repeatedly 3. **Use events for one-way communication**: If you don't need a response, use events instead ```lua theme={null} -- BAD: Callback every second CreateThread(function() while true do Wait(1000) RSGCore.Functions.TriggerCallback('getData', function(data) -- Do something end) end end) -- GOOD: Event for one-way or cache for repeated use local cachedData = nil RegisterNetEvent('updateData', function(data) cachedData = data end) -- Request once and cache RSGCore.Functions.TriggerCallback('getData', function(data) cachedData = data end) ``` *** ## Common Patterns ### Pattern 1: Permission Check ```lua theme={null} -- SERVER RSGCore.Functions.CreateCallback('checkPermission', function(source, cb, permission) cb(RSGCore.Functions.HasPermission(source, permission)) end) -- CLIENT RSGCore.Functions.TriggerCallback('checkPermission', function(hasPermission) if hasPermission then -- Show admin menu end end, 'admin') ``` ### Pattern 2: Database Fetch ```lua theme={null} -- SERVER RSGCore.Functions.CreateCallback('getPlayerStats', function(source, cb) local Player = RSGCore.Functions.GetPlayer(source) if not Player then cb(nil) return end local stats = MySQL.query.await('SELECT * FROM player_stats WHERE citizenid = ?', { Player.PlayerData.citizenid }) cb(stats[1] or {}) end) ``` ### Pattern 3: Multi-Step Validation ```lua theme={null} -- SERVER RSGCore.Functions.CreateCallback('canCraftItem', function(source, cb, itemName, amount) local Player = RSGCore.Functions.GetPlayer(source) if not Player then cb({ canCraft = false, reason = 'Invalid player' }) return end -- Check recipe exists local recipe = Config.Recipes[itemName] if not recipe then cb({ canCraft = false, reason = 'Unknown recipe' }) return end -- Check player has required items for _, ingredient in pairs(recipe.required) do if not Player.Functions.HasItem(ingredient.item, ingredient.amount * amount) then cb({ canCraft = false, reason = 'Missing ' .. ingredient.item }) return end end -- Check inventory space if not exports['rsg-inventory']:CanAddItem(source, itemName, amount) then cb({ canCraft = false, reason = 'Inventory full' }) return end cb({ canCraft = true }) end) ``` *** ## Troubleshooting ### Callback Not Responding Ensure `CreateCallback` is called before you try to trigger it: ```lua theme={null} -- Make sure this runs when resource starts RSGCore.Functions.CreateCallback('example', function(source, cb) cb('data') end) ``` Look in your server/client console for Lua errors that might prevent the callback from executing Make sure the resource containing the callback is actually started: ``` ensure your-resource ``` ### Callback Returns Nil Common causes: * Player object is nil (player left server) * Database query returned no results * Logic error in callback function Always handle nil returns: ```lua theme={null} RSGCore.Functions.TriggerCallback('getData', function(data) if not data then print('Callback returned nil') return end -- Process data end) ``` *** ## Advanced: Async/Await Pattern For cleaner code, you can wrap callbacks in promises: ```lua theme={null} -- CLIENT function GetServerDataAsync(arg1, arg2) local p = promise.new() RSGCore.Functions.TriggerCallback('example:getData', function(data) p:resolve(data) end, arg1, arg2) return Citizen.Await(p) end -- Usage CreateThread(function() local data = GetServerDataAsync('test', 123) if data then print('Got data: ' .. json.encode(data)) end end) ``` *** ## Summary * **Server Callbacks**: Client requests data from server * `CreateCallback` on server * `TriggerCallback` on client * **Client Callbacks**: Server requests data from client * `CreateClientCallback` on client * `TriggerClientCallback` on server * **Always validate** data on the server * **Always handle** nil responses * **Use events** for one-way communication * **Cache data** when possible to avoid repeated callbacks *** ## Next Steps * [Server Events Guide](/essentials/events) - One-way server-client communication * [Player Data](/essentials/playerdata) - Access and modify player data * [Server Functions Reference](/api-reference/endpoint/serverfunctionreference) - Complete function list * [Inventory Functions](/inventory/functions) - Work with inventory items *** Need help? Join the [RSG Framework Discord](https://discord.gg/rsg-redm-framework-914413479157448744)! # โ— Commands Source: https://rsg.mintlify.app/essentials/commands Complete guide to creating and using commands in RSG Framework ## Introduction RSG Framework provides a robust command system that allows you to create custom commands with permission levels, argument validation, and suggestions. Commands can be restricted to specific permission groups like admin, mod, or user. **Location**: `resources/[framework]/rsg-core/server/commands.lua` Commands are automatically registered with FiveM's native suggestion system, showing available commands and their arguments based on player permissions. *** ## Core Features ### ๐Ÿ” Permission-based Access * **User**: Available to all players * **Mod**: Moderator-only commands * **Admin**: Administrator commands * **God**: Super admin commands ### ๐Ÿ“ Argument Handling * **Required/Optional**: Control if arguments are mandatory * **Help Text**: Descriptions shown in suggestions * **Type Validation**: Validate argument types in callbacks ### โšก Auto-completion * **Dynamic Suggestions**: Commands show based on permissions * **Argument Hints**: Display help text for each argument * **Refresh System**: Update suggestions when permissions change *** ## Creating Commands ### RSGCore.Commands.Add This function allows you to register a command with a specified user level ```lua theme={null} RSGCore.Commands.Add(name, help, arguments, argsrequired, callback, permission, ...) ``` * name: `string` * help: `string` * arguments: `table` * argsrequired: `boolean` * callback: `function` * permission: `string` Example: ```lua theme={null} local arguments = { { name = 'arg 1', help = 'This will give helpful hints on what arg is for' }, { name = 'arg 2', help = 'This will give helpful hints on what arg is for' } } local argsRequired = true -- if this is true the command won't work without args entered RSGCore.Commands.Add('test', 'Trigger a test command', arguments, argsRequired, function(source) print('Congrats, you made a test command that anyone can trigger!') end, 'user') ``` ## RSGCore.Commands.Refresh This function will trigger a refresh of all commands suggestions. This is helpful for when setting permissions to a higher level, it will refresh the suggestions list so the player can now see the new commands they have access to! ```lua theme={null} RSGCore.Commands.Refresh(source) ``` * source: `number` Example: ```lua theme={null} RegisterCommand('refreshCommands', function() RSGCore.Commands.Refresh(source) print('You have refreshed all command suggestions for yourself') end, true) ``` *** ## Practical Examples ### Example 1: Basic User Command ```lua theme={null} -- Simple command any player can use RSGCore.Commands.Add('mycoords', 'Get your current coordinates', {}, false, function(source) local src = source local ped = GetPlayerPed(src) local coords = GetEntityCoords(ped) TriggerClientEvent('ox_lib:notify', src, { title = 'Coordinates', description = string.format('X: %.2f Y: %.2f Z: %.2f', coords.x, coords.y, coords.z), type = 'inform' }) end, 'user') ``` ### Example 2: Admin Command with Arguments ```lua theme={null} -- Give item to player local arguments = { { name = 'id', help = 'Player ID to give item to' }, { name = 'item', help = 'Item name from shared/items.lua' }, { name = 'amount', help = 'Amount to give (default: 1)' } } RSGCore.Commands.Add('giveitem', 'Give an item to a player', arguments, true, function(source, args) local targetId = tonumber(args[1]) local itemName = args[2] local amount = tonumber(args[3]) or 1 local Player = RSGCore.Functions.GetPlayer(targetId) if not Player then TriggerClientEvent('ox_lib:notify', source, { description = 'Player not found', type = 'error' }) return end if exports['rsg-inventory']:AddItem(targetId, itemName, amount) then TriggerClientEvent('ox_lib:notify', source, { description = 'Gave '.. amount ..'x '.. itemName ..' to player '.. targetId, type = 'success' }) end end, 'admin') ``` ### Example 3: Command with Optional Arguments ```lua theme={null} -- Heal command - heal yourself or another player local arguments = { { name = 'id', help = 'Player ID (optional, heals yourself if empty)' } } RSGCore.Commands.Add('heal', 'Heal yourself or another player', arguments, false, function(source, args) local targetId = tonumber(args[1]) or source local targetPed = GetPlayerPed(targetId) if not targetPed or targetPed == 0 then TriggerClientEvent('ox_lib:notify', source, { description = 'Invalid player', type = 'error' }) return end -- Heal the player local Player = RSGCore.Functions.GetPlayer(targetId) if Player then Player.Functions.SetMetaData('isdead', false) Player.Functions.SetMetaData('hunger', 100) Player.Functions.SetMetaData('thirst', 100) TriggerClientEvent('rsg-player:client:heal', targetId) TriggerClientEvent('ox_lib:notify', source, { description = targetId == source and 'You have been healed' or 'Player '.. targetId ..' has been healed', type = 'success' }) end end, 'admin') ``` *** ## Built-in Commands ## AdminMenu Teleports you to either a player with the given `id` or to a given `x, y, z` location **Permission level:** admin * **id or x** - (required) The player id or x coordinate * **y** - (optional) The y coordinate (required if using x for the first argument) * **z** - (optional) The z coordinate (required if using x for the first argument) Teleports you to the marked location on the map. **Permission level:** admin Allows you to fly around the map. **Permission level:** admin Toggles Player vs Player mode on the server **Permission level:** admin Toggles Player vs Player mode on the server **Permission level:** admin Removes the given `permission` from the player with the given `id`. The player must be online. **Permission level:** god Opens the server allowing everyone to join. **Permission level:** admin Closes the server for people without the correct permission. Kicks any players currently online without the required permission giving the `reason` in the kick message. **Permission level:** admin Spawns a wagon of the given `model` type. **Permission level:** admin Spawns a wagon of the given `model` type. **Permission level:** admin Deletes the vehicle you are sitting in or deletes all vehicles within 5.0 units of your position. **Permission level:** admin Gives money to a player **Permission level:** admin * **id** - (required) The `id` of the player * **type** - (required) The money type \[cash, bank etc...] * **amount** - (required) The amount to give Sets the amount of money a player has. **Permission level:** admin * **id** - (required) The `id` of the player * **type** - (required) The money type \[cash, bank etc...] * **amount** - (required) The amount to set Displays your current job name and grade **Permission level:** user Displays your current job name and grade **Permission level:** user Displays your current gang name and grade **Permission level:** user Sets a player with the given `id` to be part of the given `gang` with the given `grade` **Permission level:** admin * **id** - (required) The `id` of the player * **gang** - (required) The gang name * **grade** (required) The gang grade Sets a player with the given `id` to be part of the given `gang` with the given `grade` **Permission level:** admin * **id** - (required) The `id` of the player * **gang** - (required) The gang name * **grade** (required) The gang grade Give An Item to player **Permission level:** admin * **id** - The id of a player * **item** - The itenm of shared/items.lua * **amount** - (optional) The amount item receive of a player Give Random Items **Permission level:** god Reset the inventory of type and id/plate (ID of stash or license plate) * **type** - The type of stash / trunk / glovebox * **id** - The id of stash or license plate **Permission level:** admin Notify you of your server ID **Permission level:** user Notify you of your citizen ID **Permission level:** user Stealing between players, when the target has his hands raised **Permission level:** user Refresh Skin player **Permission level:** user Access to the menu of components, materials and engravings **Permission level:** admin Access to the info of weapon **Permission level:** admin Refresh Skin wepaon player **Permission level:** user Opens Address book for player **Permission level:** user *** ## Best Practices **Use Clear Names**: Command names should be short but descriptive * Good: `giveitem`, `setjob`, `tpm` * Bad: `gi`, `sj`, `thing` **Always Validate Input**: Never trust user input - always validate arguments ```lua theme={null} RSGCore.Commands.Add('setcash', 'Set player cash', arguments, true, function(source, args) local amount = tonumber(args[1]) if not amount or amount < 0 or amount > 1000000 then TriggerClientEvent('ox_lib:notify', source, { description = 'Invalid amount', type = 'error' }) return end -- Process valid amount end, 'admin') ``` **Provide Helpful Arguments**: Good help text makes commands easier to use ```lua theme={null} local arguments = { { name = 'id', help = 'Target player server ID (1-255)' }, { name = 'amount', help = 'Dollar amount (max: 100000)' } } ``` ### Permission Levels When choosing permission levels, follow these guidelines: | Level | Use For | | ------- | -------------------------------------------------------------- | | `user` | Safe commands any player can use (view own data, cosmetic) | | `mod` | Commands that affect other players but not severely | | `admin` | Commands that modify game state, spawn items, teleport | | `god` | Dangerous commands that can break things or affect all players | *** ## Next Steps * [Server Functions Reference](/api-reference/endpoint/serverfunctionreference) - Complete function reference * [Player Data](/essentials/playerdata) - Access player data in commands * [Callbacks](/essentials/callbacks) - Client-server communication * [Configuration](/essentials/configuration) - Configure permission levels *** Need help? Join the [RSG Framework Discord](https://discord.gg/rsg-redm-framework-914413479157448744)! # โš™๏ธ RSG Core Configuration Source: https://rsg.mintlify.app/essentials/configuration Complete guide to configuring RSG Core (config.lua) ## Introduction The `rsg-core/config.lua` file contains all the core configuration options for your RSG Framework server. This file controls player defaults, money systems, server settings, and more. **Location**: `resources/[framework]/rsg-core/config.lua` *** ## General Settings ### Max Players ```lua theme={null} RSGConfig.MaxPlayers = GetConvarInt('sv_maxclients', 48) ``` * Gets the maximum players from your `server.cfg` * Default: 48 players * Set in `server.cfg`: `sv_maxclients 48` ### Default Spawn ```lua theme={null} RSGConfig.DefaultSpawn = vector4(-1035.71, -2731.87, 12.86, 0.0) ``` * The default spawn location for new players * Format: `vector4(x, y, z, heading)` * This is used when a player has no saved position ### Update Interval ```lua theme={null} RSGConfig.UpdateInterval = 5 ``` * How often (in minutes) player data is automatically saved to the database * Default: 5 minutes * Lower values = more frequent saves but more database load ### Hide Player Names ```lua theme={null} RSGConfig.HidePlayerNames = true ``` * Whether to hide player names above their heads * `true` = Names hidden (more immersive RP) * `false` = Names visible ### Reveal Map ```lua theme={null} RSGConfig.Player.RevealMap = true ``` * Whether the map is fully revealed for players * `true` = Full map revealed * `false` = Map fog of war enabled *** ## Money System Configuration ### Money Types ```lua theme={null} RSGConfig.Money.MoneyTypes = { cash = 50, -- Starting cash bank = 0, -- โš ๏ธ DEPRECATED - kept at 0 valbank = 0, -- Valentine Bank rhobank = 0, -- Rhodes Bank blkbank = 0, -- Blackwater Bank armbank = 0, -- Armadillo Bank bloodmoney = 0 -- Illegal money } ``` * Defines all money types and their starting amounts * **cash**: Physical money in player's pocket (can be dropped/stolen) * **bank**: โš ๏ธ **DEPRECATED** - Legacy bank account (set to 0, use location-specific banks) * **valbank**: Valentine Bank account * **rhobank**: Rhodes Bank account * **blkbank**: Blackwater Bank account * **armbank**: Armadillo Bank account * **bloodmoney**: Illegal money for criminal activities (physical item when EnableMoneyItems is true) The `bank` money type is **DEPRECATED**. Always use location-specific banks (valbank, rhobank, blkbank, armbank) instead! When `EnableMoneyItems = true`, cash and bloodmoney become physical inventory items that can be dropped, traded, or stolen. **Why Multiple Banks?** * **Realism**: Players must travel to specific towns to access accounts * **Gameplay**: Creates opportunities for bank robberies and escorts * **Risk**: Traveling with cash adds danger and roleplay opportunities ### Don't Allow Minus ```lua theme={null} RSGConfig.Money.DontAllowMinus = { 'cash', 'bloodmoney' } ``` * Money types that cannot go below \$0 * These types will prevent transactions if the player doesn't have enough * Bank accounts can go negative (up to the minus limit) ### Minus Limit ```lua theme={null} RSGConfig.Money.MinusLimit = -5000 ``` * The maximum amount bank accounts can go into debt * Default: -\$5000 * Only affects money types NOT in `DontAllowMinus` ### Paycheck Timeout ```lua theme={null} RSGConfig.Money.PayCheckTimeOut = 10 ``` * How often (in minutes) players receive their job paycheck * Default: 10 minutes * Payment amount is defined in `shared/jobs.lua` ### Paycheck from Society ```lua theme={null} RSGConfig.Money.PayCheckSociety = false ``` * If `true`: Paychecks come from the society/business account (requires rsg-banking) * If `false`: Paychecks are generated (money printer) * When true, businesses need funds to pay employees ### Enable Money Items ```lua theme={null} RSGConfig.Money.EnableMoneyItems = true ``` * If `true`: Cash and bloodmoney are physical inventory items * If `false`: Cash and bloodmoney are virtual (like GTA Online) * When enabled, cash can be dropped, traded, stolen This setting makes the economy more realistic as players must physically carry cash *** ## Player Configuration ### Blood Types ```lua theme={null} RSGConfig.Player.Bloodtypes = { 'A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-', } ``` * Available blood types for players * Randomly assigned on character creation * Can be used for medical RP ### Player Defaults The `RSGConfig.Player.PlayerDefaults` table defines all default values for new characters: #### Character Info Defaults ```lua theme={null} charinfo = { firstname = 'Firstname', lastname = 'Lastname', birthdate = '00-00-0000', gender = 0, nationality = 'USA', account = function() return RSGCore.Functions.CreateAccountNumber() end } ``` * **gender**: `0` = Male, `1` = Female * **account**: Automatically generated bank account number #### Job Defaults ```lua theme={null} job = { name = 'unemployed', label = 'Civilian', payment = 10, type = 'none', onduty = false, isboss = false, grade = { name = 'Freelancer', level = 0 } } ``` * New players start as unemployed civilians * Grade 0 with \$10 payment per paycheck #### Gang Defaults ```lua theme={null} gang = { name = 'none', label = 'No Gang Affiliation', isboss = false, grade = { name = 'none', level = 0 } } ``` * New players have no gang affiliation by default #### Metadata Defaults ```lua theme={null} metadata = { health = 600, hunger = 100, thirst = 100, cleanliness = 100, stress = 0, isdead = false, armor = 0, ishandcuffed = false, injail = 0, jailitems = {}, status = {}, rep = {}, callsign = 'NO CALLSIGN', bloodtype = function() return RSGConfig.Player.Bloodtypes[math.random(1, #RSGConfig.Player.Bloodtypes)] end, fingerprint = function() return RSGCore.Player.CreateFingerId() end, walletid = function() return RSGCore.Player.CreateWalletId() end, criminalrecord = { hasRecord = false, date = nil }, } ``` **Hunger, Thirst, Cleanliness**: Scale from 0-100 * 100 = Full/Clean * 0 = Empty/Dirty **Health**: RedM uses 0-600 scale (not 0-100 like GTA) #### Inventory Defaults ```lua theme={null} weight = 35000, -- Player default weight (35kg) slots = 25, -- Player default slots ``` * **weight**: Maximum carry weight for new players (35kg = 35000 grams) * **slots**: Number of inventory slots for new players **Player Defaults vs Inventory Limits**: These are starting values for players. The actual inventory system limits are configured in `rsg-inventory/shared/config.lua`: * `MaxWeight = 120000` (120kg maximum) * `MaxSlots = 40` (40 slots maximum) **Inventory Configuration Hierarchy**: 1. **Player Defaults** (`rsg-core/config.lua`) - Starting values for new characters 2. **Inventory Limits** (`rsg-inventory/shared/config.lua`) - System-wide maximums 3. **Player-Specific** - Can be modified per player via `Player.Functions.SetPlayerData()` ```lua theme={null} -- Example: Give player more inventory space local Player = RSGCore.Functions.GetPlayer(source) Player.Functions.SetPlayerData('weight', 50000) -- Up to 50kg (still under 120kg max) Player.Functions.SetPlayerData('slots', 35) -- Up to 35 slots (still under 40 max) ``` *** ## Server Configuration ### Server Closed ```lua theme={null} RSGConfig.Server.Closed = false RSGConfig.Server.ClosedReason = 'Server Closed' ``` * `Closed = true`: Only players with admin permission can join * `ClosedReason`: Message shown to players when server is closed * Useful for maintenance or development ### Whitelist ```lua theme={null} RSGConfig.Server.Whitelist = false RSGConfig.Server.WhitelistPermission = 'admin' ``` * `Whitelist = true`: Only whitelisted players can join * `WhitelistPermission`: The ace permission required to join when whitelist is on * Players need the permission set in `server.cfg` ### PVP Settings ```lua theme={null} RSGConfig.Server.PVP = true RSGConfig.EnablePVP = true ``` * Controls whether players can damage each other * `true` = PVP enabled * `false` = PVP disabled (players cannot hurt each other) ### Discord Link ```lua theme={null} RSGConfig.Server.Discord = '' ``` * Your Discord invite link * Shown in kick messages * Example: `'https://discord.gg/your-invite'` ### Check Duplicate License ```lua theme={null} RSGConfig.Server.CheckDuplicateLicense = true ``` * If `true`: Prevents players from connecting with duplicate Rockstar licenses * Prevents multi-boxing/multiple accounts * Recommended: keep as `true` ### Permissions ```lua theme={null} RSGConfig.Server.Permissions = { 'god', 'admin', 'mod' } ``` * Available permission levels for your server * You can add custom levels (e.g., `'helper'`, `'vip'`) * Set in `server.cfg` using ace permissions: ```lua theme={null} # Example in server.cfg add_ace rsgcore.god command allow add_principal rsgcore.god group.admin add_principal rsgcore.god rsgcore.admin add_principal rsgcore.admin rsgcore.mod ``` *** ## Commands Configuration ### OOC Color ```lua theme={null} RSGConfig.Commands.OOCColor = { 255, 151, 133 } ``` * RGB color code for Out-Of-Character (OOC) chat messages * Format: `{ Red, Green, Blue }` (0-255 for each) *** ## Prompt Distance ```lua theme={null} RSGConfig.PromptDistance = 1.5 ``` * Default interaction distance for prompts (in meters) * Used by the prompt system in `rsg-core/client/prompts.lua` * Players must be within this distance to see/use prompts *** ## Example: Custom Configuration Here's an example of how you might customize your config: ```lua theme={null} -- Increase player capacity RSGConfig.MaxPlayers = GetConvarInt('sv_maxclients', 64) -- Change default spawn to Valentine RSGConfig.DefaultSpawn = vector4(-175.89, 627.01, 114.09, 180.0) -- Give players more starting money RSGConfig.Money.MoneyTypes = { cash = 250, bank = 0, valbank = 500, rhobank = 0, blkbank = 0, armbank = 0, bloodmoney = 0 } -- Enable whitelist RSGConfig.Server.Whitelist = true RSGConfig.Server.WhitelistPermission = 'whitelist' -- Disable PVP for RP server RSGConfig.Server.PVP = false RSGConfig.EnablePVP = false -- Faster paychecks RSGConfig.Money.PayCheckTimeOut = 5 -- More inventory space RSGConfig.Player.PlayerDefaults.weight = 50000 RSGConfig.Player.PlayerDefaults.slots = 30 ``` *** ## Tips & Best Practices **Save before editing**: Always backup your `config.lua` before making changes **Restart required**: Changes to `config.lua` require a full server restart to take effect **Test thoroughly**: Test all config changes on a development server before applying to production ### Performance Considerations * **UpdateInterval**: Lower values increase database writes * 5 minutes is a good balance * Don't go below 3 minutes on busy servers * **PayCheckTimeOut**: More frequent paychecks = more economy velocity * 10 minutes is standard * Consider your server's economy when adjusting ### Roleplay Considerations * **EnableMoneyItems**: Most RP servers keep this `true` for realism * **HidePlayerNames**: Set to `true` for immersive RP * **PVP**: Many RP servers disable this except in specific zones * **Whitelist**: Recommended for serious RP communities *** ## Need Help? If you're unsure about any setting, join the [RSG Framework Discord](https://discord.gg/rsg-redm-framework-914413479157448744) for support! # ๐Ÿ“ฅ Installation Source: https://rsg.mintlify.app/essentials/installation RSG Framework Installation Info ## Generate a CFX Key Creating a license key for your server is easy! Just head over toย [https://keymaster.fivem.net/](https://keymaster.fivem.net/)ย and click "New server" in the navigation menu. **Watch the below video of the Installation of a RSG RedM Server via txAdmin**