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
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)