I'm making light controls for a stage. This script turns a stage light off and on.
local ClickDetector = script.Parent.ClickDetector local StageLights = script.Parent.Parent.Parent.Parent.StageLights function LightSwitch() if StageLights.BackLeftSpotlight.SpotLight.Brightness==0.2 then StageLights.BackLeftSpotlight.SpotLight.Brightness = 1 script.Parent.BrickColor= BrickColor.new("Bright yellow") elseif StageLights.BackLeftSpotlight.SpotLight.Brightness==1 then StageLights.BackLeftSpotlight.SpotLight.Brightness = 0.2 script.Parent.BrickColor = BrickColor.new("Bronze") end end ClickDetector.MouseClick:connect(LightSwitch)
When I test the game and click on the button (which turns the light on and off), it will change color, but only on my first click. Any more clicks won't change the color again. Anyone know what I'm doing wrong? Thanks in advance.
This is not your fault, this is Roblox's fault. Your code is correct, it is just that Roblox has rounding errors. You can see this error in action when you print the Brightness when it is changed to 0.2. It will print something like 0.20000623. To fix this just edit your code to the following:
local ClickDetector = script.Parent.ClickDetector local StageLights = script.Parent.Parent.Parent.Parent.StageLights function LightSwitch() if math.floor(StageLights.BackLeftSpotlight.SpotLight.Brightness*10)/10==0.2 then StageLights.BackLeftSpotlight.SpotLight.Brightness = 1 script.Parent.BrickColor= BrickColor.new("Bright yellow") elseif StageLights.BackLeftSpotlight.SpotLight.Brightness==1 then StageLights.BackLeftSpotlight.SpotLight.Brightness = 0.2 script.Parent.BrickColor = BrickColor.new("Bronze") end end ClickDetector.MouseClick:connect(LightSwitch)
What this is doing is multiplying the brightness by 10 to make it about 2, rounding it down to make it equal 2, then dividing it by ten to make it equal 0.2.