Procedural room generation help

Hi, i’m making a game like Rooms, for those of you who aren’t familiar with it, here’s a link:

i’ve got a general gist of what i need to do, and i have previous code i could use; my question is how i can make it random and not break it.

Old Code
local visited = {}
game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		while true do
			wait(0.01)
			for i = -20,1 do
				local zPos = math.floor((char.HumanoidRootPart.Position.Z + i * 20) / 20 + 0.5) * 20
				if visited[zPos] == nil then
					visited[zPos] = script.Room:Clone()
					print("Room Cloned Successfully")
					local p = visited[zPos]

					p:SetPrimaryPartCFrame(CFrame.new(Vector3.new(0,0.25,zPos)))

					p.Parent = workspace.Room
				end
			end
		end
	end)
end)

i know this code is atrocious, but it works
my goal is to make it spawn in randomized chunks at each door.

any help is appreciated; thank you in advance

Instead of

visited[zPos] = script.Room:Clone()

do

rooms = game.ServerStorage.Rooms:GetChildren()
...
visited[zPos] = rooms[math.random(1, #rooms)]:Clone()
1 Like

i tried this, i don’t think it did anything besides give me an error in the output

edit: I will attach the modified code here in case I messed something up lolololol

Modified Code
local visited = {}
game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		while true do
			wait(0.01)
			for i = -20,1 do
				local zPos = math.floor((char.HumanoidRootPart.Position.Z + i * 20) / 20 + 0.5) * 20
				if visited[zPos] == nil then
					local rooms = game.ServerStorage.Rooms:GetChildren()
					local p = visited[zPos]
					visited[zPos] = rooms[math.random(1, #rooms)]:Clone()

					p:SetPrimaryPartCFrame(CFrame.new(Vector3.new(0,0.25,zPos)))

					p.Parent = workspace.Room
				end
			end
		end
	end)
end)

You’ll probably want to do


					visited[zPos] = rooms[math.random(1, #rooms)]:Clone()
local p = visited[zPos]

					p:SetPrimaryPartCFrame(CFrame.new(Vector3.new(0,0.25,zPos)))

Keep in mind “a = b” does not mean “a equals b” in Lua (and many other languages), it means “assign b to a”.

1 Like