How can I fix this generation problem?

I am working on a random tunnel generation that is similar to that in doors except the the tunnels can branch out and form different paths, and there is the problem. A normal tunnel has 1 exit and a splitter has 2 exits, a normal tunnel generates normally and so does the splitter but it gets stuck on the splitter and doesn’t generate anymore and sometimes it only generates 1 tunnel from the splitter and it just stops. I added a for i, v in pairs() to make sure the script checks the whole model for parts that are called Exit. I have no idea why it does that because I checked the model and made sure the parts are named correctly and still no luck.

Here is the code I am using, maybe someone will find an error in here because there aren’t any in the output.
Modulescript Code:

local tunnel = {} = require(script.TunnelInfo)
tunnel.lastTurnDirection = nil
tunnel.splitterGenerated = false
tunnel.random =

function tunnel.GetRandom(prevTunnel)
	local PossibleTunnels = workspace.ConcreteTunnelRooms:GetChildren()
	local randomTunnel = PossibleTunnels[tunnel.random:NextInteger(1, #PossibleTunnels)]
	local direction =[randomTunnel.Name]["Direction"]
	local hasMultipleExits =[randomTunnel.Name]["ExitAmount"]
	if (prevTunnel.Name == randomTunnel.Name) or (direction and direction == tunnel.lastTurnDirection) then
		return tunnel.GetRandom(prevTunnel)
	elseif hasMultipleExits and tunnel.splitterGenerated == true then
	return randomTunnel

function tunnel.Generate(prevTunnel)
	local randomTunnel = tunnel.GetRandom(prevTunnel)
	local newTunnel = randomTunnel:Clone()
	newTunnel.PrimaryPart = newTunnel.Entrance
	local exitamount = 0

	for i, v in pairs(prevTunnel:GetChildren()) do
		if prevTunnel.Parent == workspace.GeneratedConcreteTunnels then
			if v.Name == "Exit" then

				exitamount += 1



	if exitamount == 2 then
		tunnel.splitterGenerated = true

	newTunnel.Parent = workspace.GeneratedConcreteTunnels
	return newTunnel

return tunnel

Here is the ServerScript code:

local tunnel = require(script.TunnelModule)

local prevTunnel = workspace.GeneratedConcreteTunnels.ImportantParts

for i=1,10 do
	prevTunnel = tunnel.Generate(prevTunnel)
	if prevTunnel == workspace.ConcreteTunnelRooms.Splitter then
		tunnel.splitterGenerated = true

And here is a small table inside of the ModuleScript:

local tunnelInfo = {
	["LongStraight"] = {
	["ShortStraight"] = {
	["SlightLeftTurn"] = {
		["Direction"] = "Left"
	["SlightRightTurn"] = {
		["Direction"] = "Right"
	["Splitter"] = {
		["ExitAmount"] = "Two"

return tunnelInfo

Here is the code hierarchy:

And here is how the tunnels generate with the script, as you can see it only generates 1 tunnel on 1 side.

I hope someone knows how to fix it because I used everything I know.

1 Like