So It’s been 8 day’s Since I’ve been learning Lua and I’ve learned quite a lot in those 8 days.
So I made a basic gui script that changes colour of an part and closes when clicked on a button
Here is the script
Script
local player = game.Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
local close = playerGui.ScreenGui.X
local gui = playerGui.ScreenGui
local Black = playerGui.ScreenGui.TextButton
local Blue = gui.TextButton2
local Orange = gui.Textbutton3
local Open = gui.Open
close.MouseButton1Click:Connect(function() --Close Button
Black.Visible = false
Blue.Visible = false
Orange.Visible = false
print("closed")
Open.Visible = true
close.Visible = false
end)
Open.MouseButton1Click:Connect(function()-- Open Button
Black.Visible = true
Blue.Visible = true
Orange.Visible = true
print("opened")
Open.Visible = false
close.Visible = true
end)
I know it can be improved so I would like to improve the code and make it smaller and I just need some help to improve it.
Thank you
#2 - In the beginning, you define the ScreenGui and don’t use it at every time you could and should have. Additionally, a WaitForChild on the ScreenGui is safer to make sure the UI is always loaded in before proceeding. Note when you call :WaitForChild on a parent, all of it’s children will almost always be loaded in with the parent, which is why I only need to call it once on the ScreenGui. Also, since the functions connected to the events are doing the exact same thing (except for toggling true/false), you can put it all inside of one function and then call it with a value to pass to it, like this:
local player = game.Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
local sGui = playerGui:WaitForChild("ScreenGui")
local close = sGui.X
local Black = sGui.TextButton
local Blue = sGui.TextButton2
local Orange = sGui.Textbutton3
local Open = sGui.Open
local function toggleVisible(status)
Black.Visible = status
Blue.Visible = status
Orange.Visible = status
Open.Visible = not status
close.Visible = status
print(status and "closed" or "opened")
end)
close.MouseButton1Click:Connect(function() --Close Button
toggleVisible(false)
end)
Open.MouseButton1Click:Connect(function()-- Open Button
toggleVisible(true)
end)
-- Variables --
local text = "This is test"
local character = game.ReplicatedStorage.Characters:GetChildren()
-- Function --
for i,v in pairs(character) do
print(v.Name)
end
-- Other --
print(text)
I really don’t see how adding comments can improve a script other than making it easier for someone to understand, but if you are the only person that will be seeing the script it wouldn’t matter too much in that case.