Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

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)

This discussion is preserved as it was. New answers, comments, and votes are closed.