Client and server in depth · Lesson 4/4 · 9 min
Networked entities: server-side vehicles and props
Create vehicles and objects from the server so everyone sees them the same and without cheating.
If you create a vehicle only on the client, others don't see it or see it weird. The correct approach in modern FiveM is to create entities on the SERVER; that way they're synced for everyone and harder to tamper with.
-- SERVER: creates the vehicle and returns its netId
RegisterNetEvent('garaje:server:spawn')
AddEventHandler('garaje:server:spawn', function(model, coords)
local src = source
-- validate that the player is allowed (job, ownership, distance)…
local veh = CreateVehicle(model, coords.x, coords.y, coords.z, coords.w, true, true)
while not DoesEntityExist(veh) do Wait(0) end
local netId = NetworkGetNetworkIdFromEntity(veh)
TriggerClientEvent('garaje:client:setOwner', src, netId)
end)server.lua
-- CLIENT: from the netId to the local entity so you can get inside
RegisterNetEvent('garaje:client:setOwner')
AddEventHandler('garaje:client:setOwner', function(netId)
local veh = NetToVeh(netId) -- wait until it exists
local tries = 0
while not DoesEntityExist(veh) and tries < 100 do
veh = NetToVeh(netId); tries = tries + 1; Wait(10)
end
if DoesEntityExist(veh) then
TaskWarpPedIntoVehicle(PlayerPedId(), veh, -1)
end
end)client.lua
netId (network ID) is the «ID card» of an entity that's the same on every client. Server creates → sends netId → each client resolves it to its local entity with NetToVeh/NetToObj/NetToPed.
Practice what you learned
0/3¿Por qué se crean los vehículos en el SERVIDOR y no solo en el cliente?
Pista
Piensa en qué ven los OTROS jugadores.
Ordena el flujo del servidor: crear el vehículo, esperar a que exista, obtener su netId y avisar al cliente.
Coloca las líneas en el orden correcto con las flechas.
TriggerClientEvent('garaje:client:setOwner', src, netId)local veh = CreateVehicle(model, coords.x, coords.y, coords.z, coords.w, true, true)local netId = NetworkGetNetworkIdFromEntity(veh)while not DoesEntityExist(veh) do Wait(0) endPista
Primero se crea, luego se confirma que existe, después se saca el netId y por último se avisa al cliente.
Completa el cliente: resuelve el netId a su entidad local y mete al jugador dentro.
RegisterNetEvent('garaje:client:setOwner')AddEventHandler('garaje:client:setOwner', function(netId) local veh = (netId) if DoesEntityExist(veh) then TaskWarpPedIntoVehicle((), veh, -1) endend)Pista
Del netId a la entidad local con NetToVeh; el ped del jugador con PlayerPedId.
Challenge: code it yourself
Make it so that when spawning the vehicle on the server it also gets a specific license plate before notifying the client.
Write it yourself in your editor (VS Code) and test it on your server. You learn here by doing it, not by copying.
See hint
After CreateVehicle and DoesEntityExist, call SetVehicleNumberPlateText(veh, 'CRX 001').
Escribe aquí tu solución:
