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

Function does not run after calling it inside an if statement?

Hi. I'm trying to make a lamp post that glows and dims when it is nighttime and stops when it is day. I also made 2 buttons that will change the time of day when clicked.

This is the script I made (Normal script inside ServerScriptService):

-- Variables.
local lightPart = workspace.LampPost.Light
local pointLight = workspace.LampPost.Light.PointLight
local brightnessChange = 1
local timeChange = 0.03
local dayClick = workspace.LampPost.DayButton.ClickDetector
local nightClick = workspace.LampPost.NightButton.ClickDetector
local yellow = BrickColor.new("New Yeller")

-- Functions for turning light on and off.
local function turnLampPostOn()
	while true do
		wait(1)
		
		for bright = 1, 10, brightnessChange do
			pointLight.Brightness = bright
			wait(timeChange)
		end
		
		wait(1)
		
		for dim = 9, 0, -brightnessChange do
			pointLight.Brightness = dim
			wait(timeChange) 
		end
	end
end

local function turnLampPostOff()
	lightPart.BrickColor = yellow
end

-- Code for mouse click event.
dayClick.MouseClick:Connect(function()
	game.Lighting.TimeOfDay = "12:00:00"
	print("Time changed to day.")
end)

nightClick.MouseClick:Connect(function()
	game.Lighting.TimeOfDay = "00:00:00"
	print("Time changed to night.")
end)

-- In here, I want the function to work when time of day becomes midnight.
if game.Lighting.TimeOfDay == "00:00:00" then
	turnLampPostOn()
	print("Lamp turned on.")
end

if game.Lighting.LightingChanged == "12:00:00" then
	turnLampPostOff()
	print("Lamp turned off.")
end

The mouse click events are normal and change the time successfully, but the lamp post won't turn on when time becomes night. There are no errors that show in the output window, the turnLampPostOn function just won't work and even the print functions don't print.

1 answer

✓ Accepted answer

You are only running your if statement 1 time.

So your function won't get called. What you can do is make a changed event.

Easy fix with Instance:GetPropertyChangedSignal Event:

game.Lighting:GetPropertyChangedSignal("TimeOfDay"):Connect(function()
if game.Lighting.TimeOfDay == "00:00:00" then
	turnLampPostOn()
	print("Lamp turned on.")
end

if game.Lighting.TimeOfDay == "12:00:00" then
	turnLampPostOff()
	print("Lamp turned off.")
	end
end)

1 comment

0

Let me know if this works!

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