How do i improve this infinite room code

hello, 4 months ago i made this game https://www.roblox.com/games/6997073541/infinite-rooms
and the code is

local gen = game.Workspace.generation
local ccc = script.cccccc
local istouched = false

function touched()
	if not istouched == true then
		istouched = true
		if ccc.Value == true then
			local cloen = script.Parent.Parent:FindFirstChild("room"..gen.Value):Clone()
			gen.Value = gen.Value + 1
			cloen.Parent = workspace
			cloen.Name = "room"..gen.Value
							script.Parent.Position = script.Parent.Position + Vector3.new(0,0,25)
			for i,v in pairs(cloen:GetDescendants()) do
				v.Position = v.Position + Vector3.new(0,0,25)

			end
		else
			gen.Value = gen.Value + 1
			local cloneroom = script.Parent.Parent.room:Clone()
			cloneroom.Name = "room"..gen.Value
			cloneroom.Parent = workspace
							script.Parent.Position = script.Parent.Position + Vector3.new(0,0,25)
			for i,v in pairs(cloneroom:GetDescendants()) do
				v.Position = v.Position + Vector3.new(0,0,25)

			end
			ccc.Value = true
		end
		istouched = false
	end
end

script.Parent.Touched:Connect(touched)

i feel like its sufficient, i want to improve it
any ideas?

1 Like
Code
local generation = workspace.generation
local ccc = script.cccccc
local parent = script.Parent

local addedPosition = Vector3.new(0, 0, 25)
local isTouched = false

function touched()
    if not isTouched then
        local roomName = "room"..(ccc.Value and generation.Value or ""
        local clone = parent.Parent[roomName]:Clone()

        isTouched = true
        gen.Value += 1

        clone.Name = "room".. generation.Value
        clone.Parent = workspace
        parent.Position += addedPosition

        for _, descendant in ipairs(clone:GetDescendants()) do
            descendant.Position += addedPosition
        end

        ccc.Value = true
        isTouched = false
    end
end

parent.Touched:Connect(touched)
Tips

I removed the repeated code in there

I changed the name of gen into generation, but I recommend changing ccc into full words so it’s easier to read

another thing I did was turning pairs into ipairs(better performance) and changing i,v into _, descendant(easier to read and understand)

also keep in mind += can be used to shorten code
a = a + b is equal to a += b

hope this helps

2 Likes

thanks! now I see it’s faster than before, now players with high ping won’t see the sky when entering doors anymore!