So I’ve got a game which has a lot of entities, and its lagging a lot if all of them are spawned in. I’m trying to make a spawning/despawning system with different chunks. This doesn’t work and just causes more lag. Here’s my code
for i,v in pairs(game.Workspace.Spawns) do
local AI = require(game.ServerStorage.AIScripts:FindFirstChild(v.Name):Clone())
local chunk = Instance.new("Part",game.Workspace.Chunks)
chunk.Anchored = true
chunk.CanCollide = false
chunk.Transparency = 1
chunk.Position = v.Position
chunk.Size = Vector3.new(AI.Settings.ReturnIfFurtherThan*2,AI.Settings.ReturnIfFurtherThan*2,AI.Settings.ReturnIfFurtherThan*2)
chunk.Touched:Connect(function(thing)
if thing.Parent:FindFirstChild("HumanoidRootPart") and game.Players:GetPlayerFromCharacter(thing.Parent) and not chunkTouching[chunk] then
chunkTouching[chunk] = true
while chunkTouching[chunk] do
local plrInChunk = false
for i,v in pairs(game.Players:GetPlayers()) do
if v.Character and v.Character:FindFirstChild("HumanoidRootPart") then
local touching = v.Character.HumanoidRootPart:GetTouchingParts()
if table.find(touching,chunk) then
plrInChunk = true
end
end
end
if not plrInChunk then
if Spawns[chunk] then
Spawns[chunk]:Destroy()
Spawns[chunk] = nil
end
chunkTouching[chunk] = nil
return
end
if Spawns[chunk] and Spawns[chunk].Parent then continue end
local entity = game.ServerStorage.Entities:FindFirstChild(v.Name):Clone()
entity.HumanoidRootPart.CFrame = v.CFrame + Vector3.new(0,5,0)
entity.Parent = game.Workspace.Entities
Spawns[chunk] = entity
setupEntity(entity,v)
wait(5)
end
end
end)
end
I get a script timeout: exhausted allowed execution time error on table.find(touching,chunks)
It only seems to error if I approach the boss which has a larger ReturnIfFurtherThan