Hey everbody, I made a script that would turn on and off a PointLight within the game. Turning it OFF works fine, but turning it on doesn't. It should also change the colour of the switch green while on, and red while off. It turns it red, but doesn't turn it back on, or green. Here is the code. Any help is welcome.
switch=game.Workspace.Light_Switch.LightSwitch lamp=game.Workspace.LightSource.PointLight if lamp==nil then print "lamp does not exist" else print "Lamp exists" end function onClicked() if lamp.Enabled==False then switch.BrickColor=BrickColor.Green() lamp.Enabled=True else lamp.Enabled=False switch.BrickColor=BrickColor.Red() end end switch.ClickDetector.MouseClick:connect(onClicked)
Thanks for the answer that was given, it however, still does not work. If anybody could help me I would be very grateful.
The boolean constants are false
and true
, not False
and True
(see that the syntax highlighter isn't highlighting them in your code?). All Lua terms & names are case sensitive.
Tab and space your code properly.
switch = game.Workspace.Light_Switch.LightSwitch lamp = game.Workspace.LightSource.PointLight -- `lamp` cannot be `nil`. If it doesn't exist, -- accessing it will only error (so the check after is useless) -- Since you're referring to it in `game.Workspace`, you -- ought to be able to guarantee this ahead of time anyway, -- so you *shouldn't* be checking it in this script. -- If you DID doubt it for some reason, you must index with -- `:FindFirstChild("PointLight")` to avoid the error function onClicked() if lamp.Enabled == false then switch.BrickColor = BrickColor.Green() lamp.Enabled = true else lamp.Enabled = false switch.BrickColor = BrickColor.Red() end end switch.ClickDetector.MouseClick:connect(onClicked)
Note that it would be briefer to just say if lamp.Enabled then
(and obviously switch the order).
The inverting true
and false
could be turned into:
lamp.Enabled = not lamp.Enabled
and moved outside of the if, reducing the complexity of the code a little:
function onClicked() lamp.Enabled = not (lamp.Enabled); -- Flip-flop the Enabled property if lamp.Enabled then switch.BrickColor = BrickColor.Red() else switch.BrickColor = BrickColor.Green() end end