After days of headaches, I’m bringing this guide to hopefully help people that can’t figure out how to get entities to be usable in a server sided enviroment (That is, in a server-script)
First, you need to request a client to create the object for you. I wanted to make the entity as server sided as possible, So the Client Event is triggered by a server script.
[server.lua]
TriggerClientEvent("createobject",GetPlayers()[1],'prop_med_bag_01',x,y,z)
(Edit the x,y,z variables with proper coordinates)
The key part comes when creating the object. To give the object a NetId, you need to use
the ObjToNet
native + the IsNetwork
set to true
.
[client.lua]
RegisterNetEvent("createobject")
AddEventHandler("createobject",function(model,x,y,z)
local object = ObjToNet(CreateObject(GetHashKey(model),x,y,z,true,false))
TriggerServerEvent("getobject",object)
end)
You need to asign a variable to the object, because we are going to send that variable to the server using the getobject
Server Event.
[server.lua]
RegisterServerEvent("getobject")
AddEventHandler("getobject", function(object)
print(GetEntityCoords(NetworkGetEntityFromNetworkId(object)))
end)
(In this example i just print out the coordinates to the server console, but you get the point)
It’s also really important to use the NetworkGetEntityFromNetworkId
, as it will get the netid of the object you are referencing.
If you don’t use NetworkGetEntityFromNetworkId
AND ObjToNet
the server will be unable to find the object, as the getobject
server event example will only print out empty vectors: Vector3(0,0,0)
. It may also error out.
You can also use this trick when creating pickups, it also works, and for gamemodes that require players to retrieve an object, it’s pretty neat. You only need to change the CreateObject
for a CreatePickup
or CreatePickupRotate
native.
[client.lua]
RegisterNetEvent("createobject")
AddEventHandler("createobject",function(model,x,y,z)
local object = ObjToNet(CreatePickupRotate(GetHashKey("PICKUP_WEAPON_MINGUN"),x,y,z,0.0,0.0,0.0,8,250,nil,true,GetHashKey("WEAPON_MINIGUN")))
TriggerServerEvent("getobject",object)
end)
EDIT: For some reason the CreatePickup
native returns the player model and coordinates. Looking into it.
Hope this helped!