DataStore not working for apparently no reason

  1. What do you want to achieve?
    I want to save a IntValue for a player.

  2. What is the issue?
    For seemingly no reason the DataStores won’t work. I’ve also noticed that PlayerRemoving and BindToClose don’t print at all with a print at the beginning.

  3. What solutions have you tried so far?
    Changing up the code, adding pcalls etc.

My code:

local dss = game:GetService("DataStoreService")
local timeds = dss:GetDataStore("TimeStore")
print("leaderboard")

game.Players.PlayerAdded:Connect(function(plr)
	local ls = Instance.new("Folder")
	ls.Name = "leaderstats"
	ls.Parent = plr
	
	local tp = Instance.new("StringValue")
	tp.Name = "Time Played"
	tp.Parent = ls
	tp.Value = "Loading..."
	
	local t = Instance.new("IntValue")
	t.Name = "time"
	t.Parent = plr
	t.Value = timeds:GetAsync(plr.UserId) or 0
	
	
	local function convert(timee)
		-- return formatted time
		return string.format("%2i:%02i:%02i", timee/60^2, timee/60%60, timee%60)
	end
	
	while wait(1) do
		t.Value = t.Value + 1
		local convtime = convert(t.Value)
		tp.Value = convtime
	end
	
	game.Players.PlayerRemoving:Connect(function(player)
		print("player left")
		local success, err = pcall(function()
			timeds:SetAsync(player.UserId, player:FindFirstChild("time").Value)
		end)
		if success then
			print("saved successfully")
		else
			print("error saving:")
			print(err)
		end
	end)	
	
	game:BindToClose(function()
		print("closing")
		for _, v in pairs(game.Players:GetPlayers()) do
			local success, err = pcall(function()
				timeds:SetAsync(v.UserId, v:FindFirstChild("time").Value)
			end)
			if success then
				print("saved successfully")
			else
				print("error saving:")
				print(err)
			end
		end
	end)
	
		
end)
1 Like

There could be a problem here. When testing in studio or in game alone, you are the only one there. When you leave, both these events fire because the game is first closing and you are leaving. Datastore cannot handle this and it exceeds its limit. It will take a while to save the data.

If there are many people in game, then you could use the game.BindToClose event.

2 Likes

I’ve added a :IsStudio check to the BindToClose but it still doesn’t work :frowning:

1 Like

Remove the game.BindToClose event. In my opinion, you don’t really need it as of now (unless you have many players in your game every day.

This will help save your data. Plus, when the player leaves, the data is saved anyhow.

2 Likes

No idea how, but that worked! TYSM!

1 Like

BindToClose() is useful for testing DataStores while in studio since PlayerRemoving doesn’t always fire.

1 Like