Time Script Not Working When You Rejoin

Hi, I made a time script that is supposed to save your data and add one to the leaderstat every second. It does that, until you rejoin with another player in your server. Here’s the script:

local datastore = game:GetService("DataStoreService")
local ds1 = datastore:GetDataStore("TimeSave")
game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = plr
	
	local tim = Instance.new("IntValue")
	tim.Name = "Time"
	tim.Parent = leaderstats 
	

	
	tim.Value = ds1:GetAsync(plr.UserId) or 0
	ds1:SetAsync(plr.UserId, tim.Value)
	
	tim.Changed:Connect(function()
		ds1:SetAsync(plr.UserId, tim.Value)
	end)
	

	
	while true do
		
		wait(1)
		
		tim.Value = tim.Value + 1
		
	end
		
	
	
	
end)

It completely stops adding to the leaderstat when you rejoin, if you see the problem please let me know. Thanks.

1 Like

You have to load the player’s data from the data store by using ds1:GetAsync(). And save the data when player leaves.
You can do this :

local datastore = game:GetService("DataStoreService")
local ds1 = datastore:GetDataStore("TimeSave")
game.Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = plr

    local tim = Instance.new("IntValue")
    tim.Name = "Time"
    tim.Parent = leaderstats 
   
    tim.Value = ds1:GetAsync(plr.UserId) or 0

    while true do
	    wait(1)
	    tim.Value = tim.Value + 1
    end
    
end)

game.Players.PlayerRemoving:Connect(function(player)
    local tim = player.leaderstats.Time
    ds1:SetAsync(player.UserId, tim.Value)
end)
2 Likes