Local script dosen't recognize a boolean from a module script

Hey y’all, after a break from scripting I decided today to return to working on my day and night cycle, but have now run into some behavior I don’t quite understand. In my local script, I have lines of code checking wether or not a boolean from my module script is set to true or false respectively. When lockTime is true, the cycle is supposed to pause by disconnecting its heartbeat. When lockTime is false, its supposed to return to working. But for some reason, it isnt actually registering the boolean as true or false. Down below is the code from both scripts, any and all help figuring this out will be greatly appreciated <3

local Lighting = game:GetService("Lighting")
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local globalVariables = require(ReplicatedStorage.Modules.Data.globalVariables)
local currentTimeofDay = ReplicatedStorage.Values.currentTimeofDay

local function tween(l, p)
	TweenService:Create(Lighting, TweenInfo.new(l, Enum.EasingStyle.Linear, Enum.EasingDirection.In), p):Play()
end

--Change the time of day
local function changeTimeofDay()
	globalVariables.currentTime += 1
	if globalVariables.currentTime > #globalVariables.timesofDay then
		globalVariables.currentTime = 1
	end
	currentTimeofDay.Value = globalVariables.timesofDay[globalVariables.currentTime]
	print(globalVariables.timesofDay[globalVariables.currentTime])
end

--Tween sky colors
local tweenSkyCo = coroutine.create(function()
	
end)

--Change the time of day
local changeTimeCo = coroutine.create(function()
	if (Lighting.ClockTime >= 6 and Lighting.ClockTime < 6.5) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 6.5 and Lighting.ClockTime < 7) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 12 and Lighting.ClockTime < 12.5) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 17 and Lighting.ClockTime < 17.5) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 17.5 and Lighting.ClockTime < 18) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 18 and Lighting.ClockTime < 18.2) then
		changeTimeofDay()
	end
end)

--The visual time of day
local clockTime = RunService.Heartbeat:Connect(function()
	Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
end)

--Pause the current time for singleplayer content
if globalVariables.lockTime == true then
	coroutine.yield(changeTimeCo)
	clockTime:Disconnect()
elseif globalVariables.lockTime == false then
	coroutine.resume(changeTimeCo)
	clockTime = RunService.Heartbeat:Connect(function()
	Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
	end)
end
local globalVariables = {}

--Time
globalVariables.timesofDay = {"Dawn", "Morning", "Afternoon", "Evening", "Dusk", "Night"}
globalVariables.currentTime = 1
globalVariables.lockTime = true

return globalVariables

Hello! Before I can further help you, there is some additional information that could be helpful.

First, is there any error message? And if so, what is it? If there is no error message, then try adding print(globalVariables.lockTime) right above the if, elseif statement.

Also, if you are changing the lockTime value while the game is running, that could be the source of your problem. This is because the if, elseif statement in your code only runs at the very beginning of your script. So if you want the if, elseif statement to run every time globalVariables.lockTime changes, you will need additional logic for that.

hope this is helpful in some way!

Hello, to answer your first question, there are no error messages with this current script.
I just added print(globalVariables.lockTime) above the if statement, which returns true so I at least can confirm the variable in the module script is set to what I wanted. Also thanks for pointing out how I’d need additional logic for the elseif statement, I had overlooked that part.

Ok great.

Then, your if statement “should” be running, doing what it says for when lockTime is true.

To test that, you could put another print() inside the if statement to see if it runs, even though in theory it should.

If it prints, then it seems that it’s working then.

And then if you want it to change if you update the variable in the module script, then all you need to do is add that and you should be good to go.

I put more two more print statements inside the statements, and they are printing as intended. My problem now is that the day and night cycle is still continuing even though the heartbeat is disconnected. My current goal for this script is so that time will pause while the boolean is set to true, but I probably should’ve clarified that as well in my initial post, so apologies.

No problem! We can try to fix that too then.

So which part of the day/night cycle keeps going? The internal tracking of the module or the visual sun/moon in the sky?

Its the visual sun and moon in the sky, alongside the Lighting’s ClockTime ticking forward

Ok. First, we should add print statements inside each of your functions that change the visual time of day. Mainly being both the functions that say

clockTime = RunService.Heartbeat:Connect(function()
Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
end)

Maybe just add something like print(“Visual Time Updated!”) so we can see it in the output.

And then also add a print statement where you disconnect the function saying something like “disconnected time function.” The main reason for this is so that we can see if the disconnecting line is actually running, and if it ran but the time still updates.

I added the print functions as you recommended, here is what the snippet of code currently looks like.

--The visual time of day
local clockTime = RunService.Heartbeat:Connect(function()
	Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
	print("Visual time updated!")
end)

--Pause the current time for singleplayer content
print(lockTime.Value)
if lockTime.Value == true then
	print("The day/night cycle is paused.")
	coroutine.yield(changeTimeCo)
	clockTime:Disconnect(function()
		print("Disconnected time function!")
	end)
elseif lockTime.Value == false then
	print("The day/night cycle is active.")
	coroutine.resume(changeTimeCo)
	clockTime = RunService.Heartbeat:Connect(function()
		Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
		print("Visual time updated!")
	end)
end

Ok this is good!

Just remember that disconnect runs by itself (I think) so it should look like:

clockTime:Disconnect()
print("Disconnected time function!")

Instead of:

clockTime:Disconnect(function()
	print("Disconnected time function!")
end)

But then just test that, toggle the Timelock a couple times, and send what the output says.

Also, I will have to continue helping you with this later because I have to go for a little bit sorry!

Here is what the output looks like, note that the print for visual time is expectedly now firing off every frame. It also is still functioning the same way with lockTime turned on and off.


And thank you for the assistance you’ve given me thus far, you shouldn’t need to apologize because you’re busy, it’s all okay lol

What is the ChangeTimeCo coroutine for? From what I can see, you resume that thread to “start” it, but then it runs once, finishes, and wont run every again (because there is no loop). The coroutine.yield() wont do anything, as the coroutine because dead after it was ran the first time

Also be careful with coroutine.remuse(), that function is weird in the sense that, if an error happens in the coroutine, coroutine.resume() will “catch” it, and return is as an argument, like this:

local Success, Result = coroutine.resume([...])

Where success is whether or not it ran without error, and result will be the error message in case there was an error (otherwise, result can be stuff returned by the coroutine)
This is undesirable because, well coroutine’s primary purpose isn’t error handling, and unbeknownst to myself and probably others, it can hide error messages from you (it catches errors, so they don’t appear in the output window)

I would advice that you avoid using the coroutine library (at least coroutine.resume(), coroutine.yield(), coroutine.create() and coroutine.close()), as the task library simply does these things better


Another oddity I am seeing with your code, is that your if statement that checks if lockTime is true or false only runs once, when the script starts. Thus, your heartbeat connection will either be always on, or always off (if lockTime is true when you start the script, it will disconnect the heartbeat before it can run even once)

To fix this, you would need to have a loop that runs constantly, to check lockTime, like this

RunService.Heartbeat:Connect(function()
	-- If lockTime is true, we use return. When return is reached, the execution of the code in the function stops here
	if lockTime == true then return end

	Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
end)

(Which is equivalent to this)

RunService.Heartbeat:Connect(function()
	if lockTime == false then
		Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
	end
end)

There are also ways to detect when lockTime changes (instead of checking on every frame), but this check every frame is very cheap (in terms of performance), but detecting when lockTime changes can go from moderate scripting to very advanced scripting depending on the solution taken

The ChangeTimeCo coroutine was supposed to check what clocktime it is, and assign a value the next appropriate item from an array. When I first implemented this like a month ago, I had just learned about how useful coroutines were but must’ve misunderstood them to function like loops on their own, hence the oddity you’ve pointed out. The lockTime check running only once is currently the way it was because I hadn’t gotten around to making a proper function for it haha.. But what you’ve suggested regarding the straightforwardness in a loop seems like an overall good implementation for the code so far. . .

Here is what it looks like currently if you’re curious

local Lighting = game:GetService("Lighting")
local TweenService = game:GetService("TweenService")
local RunService = game:GetService("RunService")

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local globalVariables = require(ReplicatedStorage.Modules.Data.globalVariables)
local lockTime = ReplicatedStorage.Values.lockTime
local currentTimeofDay = ReplicatedStorage.Values.currentTimeofDay

local function tween(l, p)
	TweenService:Create(Lighting, TweenInfo.new(l, Enum.EasingStyle.Linear, Enum.EasingDirection.In), p):Play()
end

--Change the time of day
local function changeTimeofDay()
	globalVariables.currentTime += 1
	if globalVariables.currentTime > #globalVariables.timesofDay then
		globalVariables.currentTime = 1
	end
	currentTimeofDay.Value = globalVariables.timesofDay[globalVariables.currentTime]
	print(globalVariables.timesofDay[globalVariables.currentTime])
end

--Tween sky colors
local tweenSkyCo = coroutine.create(function()
	
end)

--Change the time of day
local changeTimeCo = coroutine.create(function()
	if (Lighting.ClockTime >= 6 and Lighting.ClockTime < 6.5) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 6.5 and Lighting.ClockTime < 7) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 12 and Lighting.ClockTime < 12.5) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 17 and Lighting.ClockTime < 17.5) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 17.5 and Lighting.ClockTime < 18) then
		changeTimeofDay()
	elseif (Lighting.ClockTime >= 18 and Lighting.ClockTime < 18.2) then
		changeTimeofDay()
	end
end)

--The visual time of day
local clockTime = RunService.Heartbeat:Connect(function(deltaTime)
	Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
	print("Visual time updated!")
end)

--Pause the current time for singleplayer content
print(lockTime.Value)
if lockTime.Value == true then
	print("The day/night cycle is paused.")
	coroutine.yield(changeTimeCo)
	clockTime:Disconnect()
	print("Disconnected time function!")
elseif lockTime.Value == false then
	print("The day/night cycle is active.")
	coroutine.resume(changeTimeCo)
	clockTime = RunService.Heartbeat:Connect(function(deltaTime)
		Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
		print("Visual time updated!")
	end)
end

lockTime.Changed:Connect(function()
	
end)

I see that you are using a BoolValue for lockTime, that is indeed one of the ways to detect when it changes, that’s a good solution. It’s not a solution I personally use, as I prefer some more complicated solutions, but it works for sure, and is probably the simplest

If you keep reworking your script, there are good chances that you’ll figure out what the issue is. Put prints around as well to get a graps of what the script is doing, and if you have questions about understanding how this or that (for example coroutines, BoolValues, anything) works, we can easily answer those questions

Chances are that by reworking and fixing the oddities, your issue could get fixed (or it’ll be much easier to fix it). I can tell you with confidence that the boolean from your module script was probably getting recognized by your script, I suspect more that the logic of your code was the culprit

this one should work: local Lighting = game:GetService(“Lighting”)
local TweenService = game:GetService(“TweenService”)
local RunService = game:GetService(“RunService”)
local ReplicatedStorage = game:GetService(“ReplicatedStorage”)

local globalVariables = require(ReplicatedStorage.Modules.Data.globalVariables)
local lockTime = ReplicatedStorage.Values.lockTime
local currentTimeofDay = ReplicatedStorage.Values.currentTimeofDay

local function tween(l, p)
TweenService:Create(Lighting, TweenInfo.new(l, Enum.EasingStyle.Linear, Enum.EasingDirection.In), p):Play()
end

local function changeTimeofDay()
globalVariables.currentTime += 1
if globalVariables.currentTime > #globalVariables.timesofDay then
globalVariables.currentTime = 1
end
currentTimeofDay.Value = globalVariables.timesofDay[globalVariables.currentTime]
print(“Time of day changed”, globalVariables.timesofDay[globalVariables.currentTime])
end

local lastTimePeriod = nil

RunService.Heartbeat:Connect(function()
if lockTime.Value == true then
return
end

Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24

local currentPeriod = nil

if (Lighting.ClockTime >= 6 and Lighting.ClockTime < 6.5) then
	currentPeriod = "Dawn"
elseif (Lighting.ClockTime >= 6.5 and Lighting.ClockTime < 12) then
	currentPeriod = "Morning"
elseif (Lighting.ClockTime >= 12 and Lighting.ClockTime < 17) then
	currentPeriod = "Afternoon"
elseif (Lighting.ClockTime >= 17 and Lighting.ClockTime < 17.5) then
	currentPeriod = "Evening"
elseif (Lighting.ClockTime >= 17.5 and Lighting.ClockTime < 18.2) then
	currentPeriod = "Dusk"
else
	currentPeriod = "Night"
end

if currentPeriod ~= lastTimePeriod then
	lastTimePeriod = currentPeriod
	for i, period in ipairs(globalVariables.timesofDay) do
		if period == currentPeriod then
			globalVariables.currentTime = i
			currentTimeofDay.Value = period
			print("Time period changed", period)
			break
		end
	end
end

end)

lockTime.Changed:Connect(function(newValue)
if newValue == true then
print(“Day/night cycle is now paused”)
else
print(“Day/night cycle is now play”)
end
end)

if lockTime.Value == true then
print(“Day/night cycle starting in paused state”)
else
print(“Day/night cycle starting in play state”)
end

I took your advice and started reworking the code a bit, and feel as though I’m now making progress! Now with the lockTime variable set as true, the day and night cycle is locked as intended. However, once I turn the boolean to false through the explorer window, I experience roughly 10 seconds of freezing before the sky corrects itself to the right time. And whenever I change the boolvalue back to true, the day and night cycle continues onward, ignoring the value.

--Pause the current time for singleplayer content
lockTime.Changed:Connect(function()
	--The visual time of day
	local clockTime = RunService.Heartbeat:Connect(function(deltaTime)
		Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
	end)
	
	if lockTime.Value == true then
		print("The day/night cycle is paused.")
		clockTime:Disconnect()
		coroutine.yield(changeTimeCo)
	elseif lockTime.Value == false then
		print("The day/night cycle is active.")
		clockTime = RunService.Heartbeat:Connect(function(deltaTime) --The visual time of day
			Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
		end)
		coroutine.resume(changeTimeCo)
	end
end)

You misunderstand coroutine.yield. This function does not accept any arguments—it is not capable of yielding a given thread. This is due to the design of cooperative multitasking, which is what coroutines achieve. In cooperative multitasking, code continues to execute asynchronously. Simultaneous execution is emulated via the leveraging of down-time.

Only one thread of execution exists. If that thread reaches a point in its work where it is met with pause, such as an external API call or a call to a yielding function like task.wait, Luau suspends that thread and resumes another so work can continue to be done.

In order for your thread to call coroutine.yield on another, it must be the current active thread. This, by definition, means the target thread to yield is already suspended. coroutine.yield is instead used to interact with its caller thread. This gives Luau developers the ability to pause the current active thread and give a more complex reasoning for its resumption.

In your case, you want your day/night cycle thread to suspend while lockTime is enabled. To achieve this, that thread must be the one to observe the lockTime state and suspend itself accordingly:

local dayNightCycle = coroutine.create(function()
    while true do
        -- The modulo operator (%) has the same precedence as multiplication and division. 
        Lighting.ClockTime = workspace:GetServerTimeNow() / 960 % 24

        if not LockTime.Value then
            task.wait()
        else
            coroutine.yield()
        end
    end
end)
local function onLockTimeChanged(locked: boolean)
    if not locked then
        coroutine.resume(dayNightCycle)
    end
end


onLockTimeChanged(LockTime.Value)

LockTime.Changed:Connect(onLockTimeChanged)

Or you can continue with your event-based path. Threads and events in this case are mutually exclusive; you should not have both implementations in your script:

local dayNightCycle: RBXScriptConnection


local function updateDayNightCycle()
    Lighting.ClockTime = workspace:GetServerTimeNow() / 960 % 24
end

local function onLockTimeChanged(locked: boolean)
    if not locked then
        dayNightCycle = RunService.PostSimulation:Connect(updateDayNightCycle)
    elseif dayNightCycle then
        dayNightCycle:Disconnect()
    end
end


onLockTimeChanged(LockTime.Value)

LockTime.Changed:Connect(onLockTimeChanged)

Currently, there is an issue with how your Heartbeat connection is setup. Everytime lockTime changes it creates a new heartbeat connection (the old one still running), although if lockTime.Value is true that new heartbeat connection gets disconnected instantly, but if lockTime.Value is false, it creates another heartbeat connection. It is never able to disconnect any existing heartbeat connection

The way to fix this, and organize it better, is to put the heartbeat connection outside the loop, then manage it from inside the loop. You can create functions that you can then call to manage it.

local clockTime = nil -- we define clockTime outside the function, so other functions can access it. However, we set it to nil, aka, no value
local function StartLoop()
	-- Check if we already have a loop running, don't want to run multiple loops at once
	if clockTime ~= nil then error("loop is already running!") end

	clockTime = RunService.Heartbeat:Connect(function(deltaTime) --The visual time of day
		Lighting.ClockTime = (workspace:GetServerTimeNow() / 960) % 24
	end)
end

local function StopLoop()
	if clockTime == nil then error("Cannot stop the loop, no loop is running")

	clockTime:Disconnect()
	clockTime = nil -- Set it back to nil so the checks works. Otherwise, it would remain as a Connection object (even though it is disconnected)
end

local function IsLoopRunning()
	-- If clockTime is not nil, then this will be true
	local IsRunning = (clockTime ~= nil) -- parentheses not needed, they are just for clarity
	return IsRunning
end

error() being a function that causes your script to error, with the message you gave it. It’s useful to catch bugs early

Note that I’m referring to the heartbeat connection as a “loop”. That is not really correct terminology, but I am too lazy to fix it

Then, your lockTime.Changed connected function can look something like this

-- Update the state of the loop depending on the value of lockTime
local function LockTimeChanged()
	-- if lock is true, and the loop is not running, the day night cycle is stopped already, so don't do anything
	-- if lock is false, and the loop is running, we don't want to start the loop again
	if lockTime.Value ~= IsLoopRunning() then return end
	
	if lockTime.Value == true then
		StopLoop()
	elseif lockTime.Value == false then
		StartLoop()
	end
end

lockTime.Changed:Connect(function()
	LockTimeChanged()
end)

-- And we want to check the value of lockTime when the game starts, and update things accordingly
LockTimeChanged()

@Ziffix’s feedback is also very valid. I would advice you just remove the coroutines

Hello I’m back! It seems you got this all figured out. Good luck with the rest of your game!