I currently track user total time played using a datastore and this is moderately reliable, but I also want to create a stat for how long their current session is (or at least play time in a day - but this is odd due to time zones). What would be the best way to do this since I have a universe? My thought is to send this count through universal teleports but that data tracking system has not been particularly reliable for me.
You could create a data template with the name of the countries and then register their time zones.
An option here would possibly be giving a session “expiration time” such as 5 minutes when a player’s data is saved. This allows for an interval where the session time is preserved if the player rejoins (eg. from an unexpected crash) or teleports to another place.
Here’s how it could possibly work
- The player’s current session time and session leave/save time are saved to the datastore.
- When the player joins the game and their data loads, the script checks for the difference between the current time and the session leave/save time. (basically time since last save)
- If the difference is less than a set threshold, preserve the previous session time. If above, reset the session time to 0
Example Code
local sessionExpirationThreshold = 300 -- 300 seconds = 5 minutes
function savePlayerData(player)
local data = {} -- data table of whatever else needs to be saved
data.sessionTime = sessionTime -- current session time of player in seconds
data.sessionLeave = os.time()
saveData(data) -- save the data table to the datastore
end
function getPlayerData(player)
local data = getData() -- get the data table from the datastore
local timeSinceLeave = os.time() - (data.sessionLeave or 0) -- get the difference between current and leave time (substitutes 0 for sessionLeave if it does not exist)
-- if the time since the last save is greater than the expiration threshold, reset session time
if timeSinceLeave > sessionExpirationThreshold then
data.sessionTime = 0
end
end
Hope this helps!