My item spawner spawns in items that players could sell for cash. I’m afraid that having a bunch of these on my map will strain the server and cause immense lag. If that is true, how can I improve my code to run efficiently on the server?
local Players = game.Players
local ServerStorage = game.ServerStorage
local ItemsFolder = ServerStorage.Items
local TrinketsFolder = ItemsFolder.Trinkets
local playersInArea = {}
local spawnDistance = 50
local trinketSpawnTime = 10
local currentTrinket
while true do
for _, plr in pairs(Players:GetPlayers()) do
local char = plr.Character
if char then
local root = char.HumanoidRootPart
local distanceFromTrinketSpawn = (root.Position - script.Parent.Position).magnitude
if distanceFromTrinketSpawn <= spawnDistance then
playersInArea[plr.Name] = plr
elseif distanceFromTrinketSpawn > spawnDistance and playersInArea[plr.Name] ~= nil then
playersInArea[plr.Name] = nil
end
end
end
local plrCount = 0
for plrName in pairs(playersInArea) do
plrCount = plrCount + 1
end
print(plrCount .. " players in area")
if plrCount > 0 then
if currentTrinket then
repeat wait(5) until #script.Parent:GetChildren() == 1
currentTrinket = nil
wait(trinketSpawnTime)
else
-- Clone a random trinket/artifact/spell into here
local chance = math.random(1, 100)
if chance > 0 and chance <= 100 then -- 100% chance for trinket for the time being
print("spawn trinket")
local trinketNum = math.random(1, #TrinketsFolder:GetChildren())
local trinket
for i, v in pairs(TrinketsFolder:GetChildren()) do
if i == trinketNum then
trinket = v:Clone()
break
end
end
trinket.Parent = script.Parent
trinket.CFrame = script.Parent.CFrame
currentTrinket = trinket
end
end
end
wait(5)
end