How could I optimize this menu script?

I’m a beginner who is learning how to script and currently I am currently stuck on how I can optimize my script so that I don’t have to reiterate my function. I have searched around and tried to use tables to my knowledge but I can’t seem to find a solution.

local MainMenu = game.Workspace.MainMenu

local Play = MainMenu.Play.SurfaceGui.TextButton
local Settings = MainMenu.Settings.SurfaceGui.TextButton
local Credits = MainMenu.Credits.SurfaceGui.TextButton



Play.MouseEnter:Connect(function(ddd)
	Play.BackgroundTransparency = 1
	Play.MouseLeave:Connect(function(ccc)
		Play.BackgroundTransparency = 0.3
	end)
end)

Settings.MouseEnter:Connect(function(ddd)
	Settings.BackgroundTransparency = 1
	Settings.MouseLeave:Connect(function(ccc)
		Settings.BackgroundTransparency = 0.3
	end)
end)

Credits.MouseEnter:Connect(function(ddd)
	Credits.BackgroundTransparency = 1
	Credits.MouseLeave:Connect(function(ccc)
		Credits.BackgroundTransparency = 0.3
	end)
end)
local MainMenu = game.Workspace.MainMenu

local textButtons = {
    Play = MainMenu.Play.SurfaceGui.TextButton,
    Settings = MainMenu.Settings.SurfaceGui.TextButton,
    Credits = MainMenu.Credits.SurfaceGui.TextButton
}

for k, textButton in pairs(textButtons) do
    textButton.MouseEnter:Connect(function()
		textButton.BackgroundTransparency = 1
	end)
    
    textButton.MouseLeave:Connect(function()
		textButton.BackgroundTransparency = 0.3
	end)
end
1 Like

Firstly, you don’t need the ddd and ccc if you’re not gonna use what’s returned.

To simplify your script further, this is the best setup I could think of

local MainMenu = game.Workspace.MainMenu

local Buttons = {
    Play = MainMenu.Play.SurfaceGui.TextButton,
    Settings = MainMenu.Settings.SurfaceGui.TextButton,
    Credits = MainMenu.Credits.SurfaceGui.TextButton,
}

local function SimulateEffect(TargetButton)
    TargetButton.BackgroundTransparency = 1
end

local function EndEffect(TargetButton)
    TargetButton.BackgroundTransparency = 0.3
end

for i, Button in pairs(Buttons) do
    Button.MouseEnter:Connect(function()
        SimulateEffect(Button)
    end)
    Button.MouseLeave:Connect(function()
        EndEffect(Button)
    end)
end

Basically, what I did was put all the buttons into a table so that the function can be connected to them in a cleaner manner by just looping through the table and connect the current object’s events to the respective functions. I also made your code modular so you can add stuff easily.

Edit:
I made some mistakes, I edited my post to fix them up.

Thank you for the quick reply and explanation of your solution! I will not use ddd or ccc in the future either.

Lol mine was the solution first but glad you found someone else’s helpful