Revise my level changing code

Im making a game that uses UI, and detects the cursors location in a UI to see if the user has passed the level. Once they mouse over a certain UI element.

This is my current code for switching out the levels.

I know there is some improvements where I can just have something that handles switching all the levels out with one fuction, rather then copy and pasting the same function several times.

local UserInputService = game:GetService("UserInputService")
local Mouse = game.Players.LocalPlayer:GetMouse()
local Main = script.Parent
local Levels = Main.Levels

--functions
function passedOne()
	Levels.LevelOne.Visible = false
	Levels.LevelTwo.Visible = true	
end

function passedTwo()
	Levels.LevelTwo.Visible = false
	Levels.LevelThree.Visible = true	
end

function passedThree()
	Levels.LevelThree.Visible = false
	Levels.LevelFour.Visible = true	
end

function passedFour()
	Levels.LevelFour.Visible = false
	Levels.LevelFive.Visible = true	
end

--gameplay
Levels.LevelOne.LevelEnd.MouseEnter:Connect(passedOne)

Levels.LevelTwo.LevelEnd.MouseEnter:Connect(passedTwo)

Levels.LevelThree.LevelEnd.MouseEnter:Connect(passedThree)

Levels.LevelFour.LevelEnd.MouseEnter:Connect(passedThree)
1 Like

Hello!
Unfortunately, you repeat a lot of code.
Imagine a situation when you have 100 levels in your game, you would have to create 100 functions and edit each.

You could rename your UI elements (Levels.LevelOne, Levels.LevelTwo…) to Levels.Level1, Levels.Level2 and then use a for loop to handle all of them.

local numberOfLevels = #Levels:GetChildren() 
for i = 1, numberOfLevels do
    Levels['Level' .. i].LevelEnd.MouseEnter:Connect(function()
        Levels['Level' .. i].Visible = false
        Levels['Level' .. (i + 1)].Visible = true
    end)
end
4 Likes