Hi Guys, so I wrote a simple obby generating code that generate random parts.
Code-
local ObbyGenerator = {}
local partsFolder = game.ServerStorage:WaitForChild("ObbyParts")
local partsFolderChildren = partsFolder:GetChildren()
local currentPart = nil
local previousPart = nil
local brick_limit = math.random(5,7)
local offset = 9
local brick_counter = 0
function ObbyGenerator:Generate()
for i=1, 10 do
local index = math.random(#partsFolderChildren)
currentPart = partsFolderChildren[index]:Clone()
currentPart.Parent = workspace
if previousPart == nil then
previousPart = currentPart
end
if currentPart == previousPart then
print("done") -- this isn't printing 10 times even when it's in loop
end
currentPart.CFrame = previousPart.CFrame * CFrame.new(0,0,(previousPart.Size.Z/2 + currentPart.Size.Z/2) + offset)
previousPart = currentPart
end
end
return ObbyGenerator
But the print(“done”) line doesn’t prints 10 times even when inside loop, what’s wrong with the code? Any help is appreciated, thanks!
Not really sure but its because you don’t reset the PreviousPart (to either nil or the next currentPart)
Really depends on how you want but probably on the last line you have to set it to nil again or just remove the if statement where you check if its nil, you set it to the currentPart anyway
Because previousPart is not the same as currentPart?
Nor it should be, as the you need the previous part to set the CFrame of the current part.
Except for the first iteration, when you specifically set the previousPart to the currentPart, previousPart will hold the reference to the previously created brick.
Comparing this two will always result false, as those are 2 separate bricks, even if those bricks are otherwise identical. That is because Lua does not compare the bricks, but the part references.
currentPart and previousPart will never be the same object in most cases so in that regard try this,
local ObbyGenerator = {}
local partsFolder = game.ServerStorage:WaitForChild("ObbyParts")
local partsFolderChildren = partsFolder:GetChildren()
local previousPart = nil
local brick_limit = math.random(5, 7)
local offset = 9
local brick_counter = 0
function ObbyGenerator:Generate()
for i = 1, 10 do
local index = math.random(#partsFolderChildren)
local currentPart = partsFolderChildren[index]:Clone()
currentPart.Parent = workspace
if previousPart then
currentPart.CFrame = previousPart.CFrame * CFrame.new(0, 0, (previousPart.Size.Z / 2 + currentPart.Size.Z / 2) + offset)
end
previousPart = currentPart
brick_counter += 1
if brick_counter >= brick_limit then
print("done")
break
end
end
end
return ObbyGenerator