• Creating many NPCs at once causes lag.
    3 replies, posted
Creating many NPCs at once causes lag. Is there a command in lua or gmod to tell the server to wait or halt so the lag does not come all at once? This code spawns no more then 10 NPCs at once. [code] local result = sql.Query( "SELECT xLoc, yLoc, zLoc, type FROM spawnController WHERE map = '" .. game.GetMap() .. "';" ) if ( !result ) then -- print("trying to get result: ") -- print("No result.") return false end for id, row in pairs( result ) do local xLoc = tostring(row['xLoc']) local yLoc = tostring(row['yLoc']) local zLoc = tostring(row['zLoc']) local vector = Vector(xLoc, yLoc, zLoc) local npcType = tostring(row['type']) if (checkSpawnArea(vector)) then newSpawn = ents.Create(npcType) newSpawn:SetPos( vector ) -- This positions the zombie at the place our trace hit. if(table.HasValue(combine, npcType)) then -- combine need weapons newSpawn:SetKeyValue( "additionalequipment", "weapon_ar2" ) end -- newSpawn:DropToFloor() if(table.HasValue(friendly, npcType)) then newSpawn:SetKeyValue("citizentype", 1) newSpawn:Fire("StartPatrolling") newSpawn:Fire("SetReadinessLow") newSpawn:Fire("SpeakIdleResponse") end newSpawn:SetKeyValue ("spawnflags", "512") newSpawn:Spawn() newSpawn:Activate() end -- print(tostring(row['type'] .. ": " .. tostring(row['xLoc']) .. ", " .. tostring(row['yLoc']) .. ", " .. tostring(row['zLoc']))) end [/code]
replace newSpawn:Spawn() newSpawn:Activate() with timer.Create("npcspawn"..tostring(newSpawn), math.Rand(0,10), 1, function() newSpawn:Spawn() newSpawn:Activate() end)
Spawning citizens are we? The lag comes from the game having to load every ressource related to each of them. Precaching them might help.
Why use math.Rand? There are bound to be NPCs that are spawned at the same time. Use: [lua]for id, row in pairs( result ) do -- more code timer.Create("npcspawn"..tostring(newSpawn), id, 1, function() newSpawn:Spawn() newSpawn:Activate() end) end[/lua] Or, if the id is not a number, just use a second variable i that you set to an initial value, and increment at the end of the loop.
Sorry, you need to Log In to post a reply to this thread.