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

How to Synchronize a Timer?

What would be the best way to go about synchronizing a timer with every player and having a local gui display the time?

So far I have a timer that 'works', but each player's timer is thrown off depending on when they joined the game.

Script in StarterGUI

local TextLabel = script.Parent

local seconds = game.Workspace.seconds.Value
local minutes = game.Workspace.minutes.Value

while true do
	if seconds == 60 then
		minutes = minutes + 1
		seconds = 0
	else
		seconds = seconds + 1
	end
	print(minutes .. " minutes " .. seconds .. " seconds")

	TextLabel.Text = string.format("%.2d:%.2d", minute, ticks)

	wait(1)
end

1 comment

0

Handle the time on the server and not the client, ez solution.

1 answer

A solution you could use is to utilize a IntValue and have the client detect the change via the Changed event. For example...

Server Script:

-- Script
local Minutes = Instance.new("IntValue", game.ReplicatedStorage) -- Create a new IntValue and parent it to the ReplicatedStorage service, naming it "Minutes"
Minutes.Name = "Minutes"
local Seconds = Instance.new("IntValue", game.ReplicatedStorage) -- Ditto
Seconds.Name = "Seconds"

while true do
	for Time = 157, 1, -1 do -- Count down the time via a for loop (157 is 2 minutes 37 seconds)
		Minutes.Value = math.floor(Time / 60)
		Seconds.Value = math.floor(Time % 60)
		wait(1)
	end
end

Client Script:

-- LocalScript
local Minutes = game.ReplicatedStorage.Minutes -- Set the variable to the "Minutes" IntValue
local Seconds = game.ReplicatedStorage.Seconds -- Ditto

local function UpdateTime() -- Runs whenever Minutes or Seconds changes
	TextLabel.Text = string.format("d:d", Minutes.Value, Seconds.Value) -- Changes the text to show the time
	-- The website isn't showing the format % 02 d : % 02 d, so to produce a similar result you could do...
--	TextLabel.Text = ((Minute.Value < 10) and "0"..Minute.Value or Minute.Value) .. ":" .. ((Seconds.Value < 10) and "0"..Seconds.Value or Seconds.Value)
end

Minutes.Changed:Connect(UpdateTime) -- Fires every time its Value property changes
Seconds.Changed:Connect(UpdateTime) -- Ditto

Doing this would allow the time to synchronize for every player.

More information on what was used if interested- IntValues ReplicatedStorage Loops IntValue.Changed

Hope this helped :thumbsup:

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