Hello everyone,
I am trying to create a survival mode script. The idea is to spawn a bunch of aggressive NPCs at some specific positions on the map and have the players fight them. I am running into a bunch of issues when I try to sync the created peds between multiple clients. I have tried to look for an answer on the internet or the official docs for a few days, but I can’t figure it out. Any help or suggestions will be helpful at this point.
So here we go.
On the client side, I am spawning the NPCs like this:
for k, v in pairs(Hostiles) do
if Hostiles[k] then
-- create hostile ped
local hostile = v
local coords = hostile.spawnCoords
local pedEntityID = CreatePed(4, HostilesModel, coords.x, coords.y, coords.z, coords.w, true, false)
-- network ped
SetEntityAsMissionEntity(pedEntityID, true, true)
NetworkRegisterEntityAsNetworked(pedEntityID)
local netID = PedToNet(pedEntityID)
NetworkSetNetworkIdDynamic(netID, false)
SetNetworkIdCanMigrate(netID, true)
SetNetworkIdExistsOnAllMachines(netID, true)
-- save netID on server
TriggerServerEvent("server:RegisterNewHostileNPC", k, netID)
end
end
This works great when I first log in to the server or when I restart the resource. The NPC is spawned in the correct location and I can get back the entityID and netID.
Then I have an event on the server to reload the exiting NPCs from network IDs if they exist. The idea is that I should be able to see the NPC if I quit and then join the server again. Here is the client-side code that handles that.
... function(key, netID) ...
clientHostiles[key] = {
exists = false,
pedEntityID = nil,
netEntityID = nil
}
if netID ~= nil then
if DoesEntityExist(NetToEnt(netID)) and NetworkDoesNetworkIdExist(netID) then
NetworkRequestControlOfNetworkId(netID)
NetworkRequestControlOfEntity(NetToEnt(netID))
clientHostiles[key].netEntityID = netID
clientHostiles[key].pedEntityID = NetToEnt(netID)
clientHostiles[key].exists = true
end
end
The problem is that NetToEnt(netID) always returns 0 in this case. No matter where I am on the map, it is always 0. I also want to mention that I tried using NetToPed(netID) instead and got back the same result.
An even more interesting thing that happens is that if I spawn any other entity, like a vehicle from the admin menu, it will assign the entityID of this object to the existing netID.
Does anyone know what is going wrong in this flow? Or is this completely wrong?