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

Why won't my light switch script work proplerly more than once???

Asked by 4 years ago
Edited by Azarth 4 years ago

Hi everyone! I'm just a noob scripter here trying to create a light that will turn on the green light then I can click to open the door and it auto closes, then turns on the red light. I want the door and the red light to stay locked for a time then the red light goes off and the green light will light up to indicate the door is ready to be clicked on again. So far the script below only works the first time thru, after that it's stuck on a color and wont change...can anyone help me solve this?

on = false
script.Parent.ClickDetector.MouseClick:connect(function(click)
    if on == false then
        on = true
        script.Parent.GLight.PointLight.Enabled = true
        else
    end
    wait(4)
    on = false
    script.Parent.GLight.PointLight.Enabled = false
    wait(.01)
    while wait do
        if on == false then 
            on = true
            script.Parent.RLight.PointLight.Enabled = true
        else
    end
    wait(6.5)

    on = false
    script.Parent.RLight.PointLight.Enabled = false
    wait(.01)

    on = true
    script.Parent.GLight.PointLight.Enabled = true
end
end)

Thank you everyone!

1 answer

Log in to vote
1
Answered by
Azarth 3141 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

To answer your question specifically, it wasn't working because the while loop never broke, so it was stuck there. Additionally, there are a few things in there that serve no purpose, the while loop for instance and the various elses as well as misplaced ends. Your "Debounce" was outside of the scope as well, so that wasn't doing anything.

Always make your variables local unless they need to be used globally. Learning about scope will help you with when to use which. Also, make variables easily distinguishable from other variables. "On" isn't very descriptive when you start writing bigger scripts.

Finally, always monitor your output, this is your lifeline, it's where you will spend most of your time. TopBar > View > Output

local Root = script.Parent
local GLight = Root:WaitForChild('PointLight')
local PointLight = GLight:WaitForChild("PointLight")
local InProgress = false

script.Parent:WaitForChild("ClickDetector").MouseClick:Connect(function()
    if not InProgress then
        InProgress = true
        -- A loop is easier than doing it manually
        for i = 1, 4 do
            -- Make opposite of Enabled
            PointLight.Enabled = not PointLight.Enabled 
            -- Ternary operator same as if else
            wait(i == 1 and 4 or i == 2 and 6.5 or 0.1)
        end 
        InProgress = false
    end
end)
Ad

Answer this question