Hello, I’m not much of a frontend developer, but over the years I’ve learned a few things to make decentish code, but I’d like to get some help on improving more. My go to approach for UI is just looping through the PlayerGui
and setting up button events on anything that’s a button and then using a open and close menu function pretty simple. The only issue is I feel like it’s a bit messy to work with since it requires each button or frame to have a module to handle the button logic.
function buttonAction(button,action)
local frame = button:FindFirstAncestorOfClass("Frame")
if frame:FindFirstChild("DISABLED") then
return
end
if script.parent:FindFirstChild(frame.Name) then
local module = require(script.Parent[frame.Name])
if action == "pressed" and module[button.Name] then
module[button.Name](button,frame)
elseif action == "enter" and module[button.Name.."Enter"] then
module[button.Name.."Enter"](button,frame)
elseif action == "leave" and module[button.Name.."Leave"] then
module[button.Name.."Leave"](button,frame)
end
else
warn("No module with name",frame.Name)
end
end
local function connectEventsToButton(button)
if not button then return end
button.MouseEnter:Connect(function()
buttonAction(button,"enter")
end)
button.MouseLeave:Connect(function()
buttonAction(button,"leave")
end)
button.MouseButton1Click:Connect(function()
buttonAction(button,"pressed")
end)
end
local function setupButtons()
for _,button in ipairs(playerGui:GetDescendants()) do
if button:IsA("TextButton") or button:IsA("ImageButton") then
connectEventsToButton(button)
end
end
screenGui.DescendantAdded:Connect(function(child)
if child:IsA("TextButton") or child:IsA("ImageButton") then
connectEventsToButton(child)
end
end)
end
-- Not sure what to call this yet, but makes sure that the main menu is visible
-- and nothing else.
local function test()
game.Lighting.MainMenuBlur.Enabled = true
mainMenuGui.Enabled = true
screenGui.Enabled = false
for _,frame in pairs(screenGui:GetChildren()) do
if frame:IsA("Frame") then
frame.Visible = false
end
end
end
function UI:openMenu(menuID)
local newMenu = screenGui[menus[menuID]]
if not newMenu then
warn("Invalid menu ID:", menuID)
return
end
if #menuStack > 0 then
-- Hide the previous menu
menuStack[#menuStack].Visible = false
end
-- Add the new menu to the stack and show it
table.insert(menuStack, newMenu)
newMenu.Visible = true
end
function UI:closeMenu()
if #menuStack == 0 then return end
-- Hide the current menu
menuStack[#menuStack].Visible = false
table.remove(menuStack)
end