How do I make a timer that saves?
For example, let’s say I’m in a game and the timer is at 30 minutes and I leave, when I rejoin in 5 minutes it would be at 25, is this possible, if so how?
How do I make a timer that saves?
For example, let’s say I’m in a game and the timer is at 30 minutes and I leave, when I rejoin in 5 minutes it would be at 25, is this possible, if so how?
You’d use DataStoreService for storing the time they left with :SetAsync() on game.Players.PlayerRemoved
and game:BindToClose()
, using os.date(“*t”). Hence, once the player reconnects by game.Players.PlayerAdded
, you can achieve their data with :GetAsync() and compare their time, in the data, with os.difftime - then subtract it.
My game (yet to be released) has a shop that refreshes every real-time hour, and to achieve this effect I used Data stores. What I did was I simply saved to the datastore the last time the shop was saved with os.time(), it returns the number of seconds that have passed since the Unix epoch (1 January 1970).
Lets say your game starts and there’s no timer yet, so you start the 30 minutes timer and save the os.time() to the datastore as soon as the timer starts. What you want to do is once someone joins the game (and if there’s no timer, you’ll get the one that already began), you are going to get the os.time() you saved to that data store and subtract it for the latest one, it will give you the number of seconds that passed since the last timer started.
With that, all you have to do is convert the seconds to minutes, which all you need to do is multiply the seconds by 60.
Here’s an example:
local last_time = MyDataStore:GetAsync("Timer")
local Seconds_Elapsed = os.time() - last_time
local Minutes_Remaining = Seconds_Elapsed * 60
Timer.Text = tostring(Minutes_Remaining) --Just an example
I’m not really familiar with scripting, would you mind going into a bit more depth?
Apologies for the late response, to be able to help you fully and get the basics down, I must know if you know how to use datastores to save/load data? Without them or some other external server to save data, what you’re trying to achieve would be impossible. This is fairly advanced