Is there a more efficient and cleaner way to write this UI code?

I’ve been working on my game’s UI for a few days now. I also have started coding the UI. However, I feel that the code I am using for the MouseEnter and MouseLeave functions for each button is repetitive and hard to read. Note I haven’t been programming in awhile.

By that, I want to find a way to clean up my code and I also want to know if there is a more efficient way to write it(to shorten it and for readability)

local frame = script.Parent

local backpack = frame.backpack
local diary = frame.diary
local settingS = frame.settings
local gacha = frame.gacha
local event = frame.events
local close = frame.close
  --enter/leave functions

    backpack.MouseEnter:Connect(function()
    	backpack.ImageColor3 = Color3.fromRGB(149, 149, 149)
    	backpack.TextLabel.Visible = true
    end)

backpack.MouseLeave:Connect(function()
	backpack.ImageColor3 = Color3.fromRGB(255,255,255)
	backpack.TextLabel.Visible = false
end)


diary.MouseEnter:Connect(function()
	diary.ImageColor3 = Color3.fromRGB(149, 149, 149)
	diary.TextLabel.Visible = true
end)
diary.MouseLeave:Connect(function()
	diary.ImageColor3 = Color3.fromRGB(255,255,255)
	diary.TextLabel.Visible = false
end)

event.MouseEnter:Connect(function()
	event.ImageColor3 = Color3.fromRGB(149, 149, 149)
	event.TextLabel.Visible = true
end)
event.MouseLeave:Connect(function()
	event.ImageColor3 = Color3.fromRGB(255,255,255)
	event.TextLabel.Visible = false
end)

gacha.MouseEnter:Connect(function()
	gacha.ImageColor3 = Color3.fromRGB(149, 149, 149)	
	gacha.TextLabel.Visible = true
end)
gacha.MouseLeave:Connect(function()
	gacha.ImageColor3 = Color3.fromRGB(255,255,255)
	gacha.TextLabel.Visible = false
end)


settingS.MouseEnter:Connect(function()	
	settingS.ImageColor3 = Color3.fromRGB(149, 149, 149)
	settingS.TextLabel.Visible = true
end)
settingS.MouseLeave:Connect(function()
	settingS.ImageColor3 = Color3.fromRGB(255,255,255)
	settingS.TextLabel.Visible = false
end)
1 Like

Since all of the objects are children of your main frame, you can just loop through all of the frame’s children and connect the events inside that loop. I have attached an untested example that I quickly wrote in Notepad below:

local frame = script.Parent

local backpack = frame.backpack
local diary = frame.diary
local settingS = frame.settings
local gacha = frame.gacha
local event = frame.events
local close = frame.close

for i,v in pairs(frame:GetChildren()) do
	-- check if the objects can actually be moused over
	
	v.MouseEnter:Connect(function()
		v.ImageColor3 = Color3.fromRGB(149, 149, 149)
		v.TextLabel.Visible = true
	end)

	v.MouseLeave:Connect(function()
		v.ImageColor3 = Color3.fromRGB(255,255,255)
		v.TextLabel.Visible = false
	end)
end
4 Likes