Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is there a more efficient way to write this?

Asked by 8 years ago

Please make your question title relevant to your question content. It should be a one-sentence summary in question form.

Hey, guys~ Here is my code:

l1 = script.Parent.Parent.Layout1
l2 = script.Parent.Parent.Layout2
l3 = script.Parent.Parent.Layout3
l4 = script.Parent.Parent.Layout4
l5 = script.Parent.Parent.Layout5
l6 = script.Parent.Parent.Layout6
l7 = script.Parent.Parent.Layout7
clicked = false

function onClick()
    if l1 and l2 and l3 and l4 and l5 and l6 and l7 and clicked == false then
        clicked = true
        l1.Visible = true -- ON
        l2.Visible = false
        l3.Visible = false
        l4.Visible = false
        l5.Visible = false
        l6.Visible = false
        l7.Visible = false
        wait()
        clicked = false
    end
end
script.Parent.MouseButton1Down:connect(onClick)

The code itself works fine, but it is copied and pasted to seven different locations and I have to change which layout visibility is true and false for each one. Is there a more efficient way to write this?

1 answer

Log in to vote
2
Answered by 8 years ago

Starting with your redefinitions So when you have many things that share the same name, a for loop becomes your best friend. It helps you using the ending numbers.

I didn't know exactly what you were doing with the .Visible property, so I left it out. The code below just checks to see if the Layout items exist and clicked == false.

clicked = false

function onClick()
    local all7 = true

    for i = 1, 7 do --Check to see if the buttons exist, if not set all7 to false.
        if script.Parent.Parent:FindFirstChild("Layout"..i) == nil then
            all7 = false
        end
    end

    if all7 and clicked == false then
        clicked = true
        --do things
        wait()
        clicked = false
    end
end

script.Parent.MouseButton1Down:connect(onClick)
Ad

Answer this question