So this code just generates a road and places it in front of the next. A bit like doors room generation. Now I was just wondering if there is any way I could make it more optimized or if there is a memory leak from it due to the connections being made. Thanks
Code:
local ServerS = game:GetService('ServerStorage')
local Roads = ServerS:WaitForChild('Roads'):GetChildren()
local MadeRoads = {}
local LastNumber
local LastRoad
local Handler = {}
Handler.CreateRoad = function()
local LastPosition
local PickedNumber = math.random(1,#Roads)
if LastNumber ~= nil then
if PickedNumber == LastNumber then
repeat
PickedNumber = math.random(1,#Roads)
task.wait(0.001)
until PickedNumber ~= LastNumber
end
end
local NewRoad = Roads[PickedNumber]:Clone()
LastNumber = PickedNumber
if not LastRoad then
LastPosition = Vector3.new(-NewRoad.PrimaryPart.Size.X/2,0,0)
else
LastPosition = LastRoad.PrimaryPart.Position
end
NewRoad:PivotTo(CFrame.new(LastPosition + Vector3.new(NewRoad.PrimaryPart.Size.X,0,0)))
NewRoad.Parent = game.Workspace.Roads
print(NewRoad.Name)
table.insert(MadeRoads,NewRoad)
--task.spawn(function()
Handler.ControlRoad(NewRoad)
--end)
LastRoad = NewRoad
return NewRoad
end
Handler.ControlRoad = function(Road)
local Debounce = false
local Debounce1 = false
Road.Start.Touched:Connect(function(hit)
if not hit.Parent then
return
end
if not hit.Parent:FindFirstChild("Humanoid") then
return
end
if Debounce == true then
return
end
Debounce = true
if table.find(MadeRoads,Road) == 3 then
MadeRoads[1]:Destroy()
table.remove(MadeRoads,1)
end
return
end)
Road.End.Touched:Connect(function(hit)
if not hit.Parent then
return
end
if not hit.Parent:FindFirstChild("Humanoid") then
return
end
if Debounce1 == true then
return
end
Debounce1 = true
LastRoad = Handler.CreateRoad()
LastRoad = Handler.CreateRoad()
return
end)
return
end
return Handler