How would I go about make a counter that shows how long the player has been playing right now?
I was thinking of making a counter that just goes up, but I am a little bit confused to achieve this
Help will be appreciated
Thanks
GreenTreeGamingYT
How would I go about make a counter that shows how long the player has been playing right now?
I was thinking of making a counter that just goes up, but I am a little bit confused to achieve this
Help will be appreciated
Thanks
GreenTreeGamingYT
Hi, you could add a value into the Player called Time and increase it every second then save it in datastore.
So I would use a while loop and increase the Time counter while using wait(1), right?
Yeah, I recommend not using while loop and use RunService.Stepped.
Here is a code example
local RunService = game:GetService("RunService")
RunService.Stepped:Connect(function()
end)
Use this code, I made while back ago It should save with datastore to
local DataStoreService = game:GetService("DataStoreService")
local CurrencyDataStore = DataStoreService:GetDataStore("CurrencyDataStore")
local RunService = game:GetService("RunService")
function PlayerJoined(Player)
local Success, KeyInfo
local CurrencyData
Success, CurrencyData, KeyInfo = pcall(function()
return CurrencyDataStore:GetAsync(Player.UserId)
end)
local Leaderstats = Instance.new("Folder")
Leaderstats.Name = "leaderstats"
Leaderstats.Parent = Player
local Time = Instance.new("IntValue")
Time.Name = "Currency"
Time.Parent = Leaderstats
Time.Value = 0
while task.wait(1) do
Time.Value += 1
end
end
function PlayerLeft(Player)
local Success, Errormessage = pcall(function()
CurrencyDataStore:SetAsync(Player.UserId, Player.leaderstats.Currency.Value)
end)
if not Success then
print(Errormessage)
end
end
function OnShutDown()
task.wait(3)
end
game.Players.PlayerAdded:Connect(PlayerJoined)
game.Players.PlayerRemoving:Connect(PlayerLeft)
game:BindToClose(OnShutDown)
Use tick()
.
local gamestarted = tick()
print(tick() - gamestarted)
-- services --
local Players = game:GetService('Players')
-- events --
Players.PlayerAdded:Connect(function(player)
-- load data --
while player do task.wait(1)
player.Data.TimePlayed.Value += 1
end
end)
Doesn’t that just show how long the server has been up and running?
Actually no, tick() is time that has passed since 1st of january of 1970. You could use tick() for time played counter, but wouldn’t recommend it since it’s deprecated.
Oh yeah. I have not read the title correctly
I will try out the following ideas in a new game and see if they work. I will reply back soon
Thank you @lilmazen1234, your code works like a charm. I will use the toMS() function to make it readable and change up the data store. Thanks a lot!