Tracking time in Leaderstats

Hello! In my RP game I am trying to make it whenever someone joins my game that the leaderboard will start tracking how long they have been active for in the game. Currently I have been reading about Datastores and leaderstat tutorials on youtube and the Roblox developer articles. So far my script is this
Script

local Players = game:GetService("Players")
 
local groupId = (GroupId)
 
Players.PlayerAdded:Connect(function(Player)
    local Leaderstats = Instance.new("Folder", Player)
    Leaderstats.Name = "leaderstats"
   
    local RankText = Instance.new("StringValue", Leaderstats)
	    RankText.Name = "Rank"
	
	local Leaderstats = Instance.new("Folder", Player)
    Leaderstats.Name = "leaderstats"
   
    local tp = Instance.new("StringValue", Leaderstats)
    tp.Name = "Time played"
   
    local Rank = Player:GetRoleInGroup(groupId)
    RankText.Value = Rank

end)
If There is any Key information that I’m missing or any documentation that I can look at that would be great as I’m still a noob at this and I started trying to script as some sort of a hobby. :slight_smile:

1 Like

You could use a while loop:

while wait(1) do -- Making a wait 1 loop
tp.Value = tp.Value + 1 --Adding the time onto the stats
end
2 Likes

I would not recommend to use a while wait loop, mainly because they are not guaranteed to fire when you want them to, more information can be found here.

You can use heartbeat instead and check to see if 1 second has passed since the last update.

local RunService = game:GetService("RunService")
local NextStep = tick()


RunService.Heartbeat:Connect(function()
	if tick() >= NextStep then
		NextStep = NextStep + 1
		tp.Value = tp.Value + 1
	end
end)
1 Like

local Players = game:GetService(“Players”)

local groupId = (GroupId)

Players.PlayerAdded:Connect(function(Player)
local Leaderstats = Instance.new(“Folder”, Player)
Leaderstats.Name = “leaderstats”

local RankText = Instance.new("StringValue", Leaderstats)
    RankText.Name = "Rank"


local Rank = Player:GetRoleInGroup(groupId)
    RankText.Value = Rank

end)

local RunService = game:GetService(“RunService”)
local NextStep = tick()

local Leaderstats = Instance.new(“Folder”, Player)
Leaderstats.Name = “leaderstats”

local tp = Instance.new("StringValue", Leaderstats)
tp.Name = "Time played"

RunService.Heartbeat:Connect(function()
if NextStep >= tick() then
NextStep = NextStep + 1
tp.Value = tp.Value + 1

end
end)
I may have swapped some of the code around and it refuses to show up on the leaderboard.

A tutorial

2 Likes

Sounds like a Good tutorial I’ll watch thank you!