Server script timing out

I’m trying to create a spawning system where a large part is checking for specific objects and spawning more if there is not a sufficient amount. However, my script is timing out right before spawning the object spawns during the repeat loop, and I am unable to find the cause. Any help would be appreciated, I have not been able to find any posts that relate to this issue :frowning:

Fixes I’ve already tried:
Creating collision groups

local ZoneDetector = script.Parent
local RP = game:GetService("ReplicatedStorage")

local function GrassSpawn()
	
	while task.wait(3) do 
		local PartsInZone = ZoneDetector:GetTouchingParts()
		local CurrentGrass = 0
		
		for i, v in pairs(PartsInZone) do
			if PartsInZone.Parent == "GrassMono" or PartsInZone.Parent == "GrassDuo" or PartsInZone.Parent == "GrassTrio" then 
				CurrentGrass += 1
			end
		end
		
		if CurrentGrass <= 8 then 
			local CurrentGrassArray = {
				RP.Plants.Grass.GrassDuo,
				RP.Plants.Grass.GrassMono,
				RP.Plants.Grass.GrassTrio,
			}
			local randomGrass = CurrentGrassArray[math.random(1, #CurrentGrassArray)]
			
			local GrassSpawnDetect = RP.Plants.Grass.GrassSpawnDetect:Clone()
			GrassSpawnDetect.Parent = game.Workspace
			GrassSpawnDetect.CFrame = ZoneDetector.CFrame * CFrame.new(math.random(-150,150),-5,math.random(-150,150))
			GrassSpawnDetect.CollisionGroup = "Detector"
			task.wait(0.1)
			local GrassSpawnObstruct = GrassSpawnDetect:GetTouchingParts()
			
			if GrassSpawnObstruct == nil then 
				randomGrass:Clone()
				randomGrass.CFrame = GrassSpawnDetect.CFrame * CFrame.new(0,-1,0)
				randomGrass.Parent = game.Workspace
				GrassSpawnDetect:Destroy()
				print("Grass Spawned!")
			else
				repeat
					GrassSpawnDetect.CFrame = ZoneDetector.CFrame * CFrame.new(math.random(-150,150),-5,math.random(-150,150))
					GrassSpawnObstruct = GrassSpawnDetect:GetTouchingParts()
				until GrassSpawnObstruct == nil
				task.wait(0.1)
				randomGrass:Clone()
				randomGrass.CFrame = GrassSpawnDetect.CFrame * CFrame.new(0,-1,0)
				randomGrass.Parent = game.Workspace
				GrassSpawnDetect:Destroy()
				print("Grass Spawned after difficulty!")
			end
		end
	end
end

task.wait(5)
task.spawn(GrassSpawn)
1 Like

GetTouchingParts will return a table, so GrassSpawnObstruct will never be nil. Instead check for #GrassSpawnObstruct == 0, in which an empty table is returned and there are no obstructions.

Also, having a repeat until like this is dangerous, and with the right RNG or the map setup such that a valid spawn is not possible/very unlikely can cause the same timeout issue at random. You should use a task.wait() occasionally in this loop to make sure it can never crash.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.