Currently, I have four items in my model and I want to turn off the visibility (if it is enabled) of the other three models. However, so far I have done this using three statements but I was wondering whether there is a quicker way to do this. Here is my code so far:
else step2.TextLabel.Text = "Step 2: Choose a drink:" step2.Visible = true step2.Main.Visible = false step2.Sides.Visible = false step2.Dessert.Visible = false step2.Drink.Visible = true
Is there a more efficient way of doing this?
You could always do
step2.Main.Visible, step2.Sides.Visible, step2.Dessert.Visible = false, false, false
which is Lua's version of multiple assignment but I don't know that it's any more efficient, and it certainly doesn't look any nicer.
A loop is also an option, but it'd hardly seem appropriate for changing a mere three things, and would actually use quite a bit more resources, making it far less "efficient".
EDIT: After doing some speed tests, it looks like Lua's multiple assignment is faster than individual statements, so that might be the best option if you're going for efficiency.
You can usually replace repetitive code with a simple loop.
We will use the Instance:GetChildren()
method to get the children inside of step2
.
local step2Children = step2:GetChildren()
Then we can create a for loop to go over each child in the resulting table
local step2Children = step2:GetChildren() for i,v in pairs(step2Children) do end
In the for loop above, i
is the index and v
is the value. The index isn't important to us right now, so we will focus on v
, which will represent each child of step2
. We just need to set Visible
to false for v
.
local step2Children = step2:GetChildren() for i,v in pairs(step2Children) do v.Visible = false end
Now there could be a problem. If you have something in there that isn't a GuiObject, it will cause an error. This isn't a huge deal but it's better to handle it than to leave it. We just have to check if v
is a GuiObject before setting Visible
to false.
local step2Children = step2:GetChildren() for i,v in pairs(step2Children) do if v:IsA("GuiObject") then v.Visible = false end end
And if you want to make it a bit neater, you can remove the first line and merge it with the second.
for i,v in pairs(step2:GetChildren()) do if v:IsA("GuiObject") then v.Visible = false end end
Hopefully this helps!