Can someone help me with datastore not working

I’m trying to make a game where there are 2 leaderstats, your level and your time.
The time goes up every second, and I have a datastore that doesnt seem to be working to keep it. PLEASE HELP.

Errors:
None

Services:
Yeah they are on im not that dumb lol

The Script:
image

Datastore:

local ds = game:GetService("DataStoreService"):GetDataStore("SaveData")
game.Players.PlayerAdded:Connect(function(plr)
	wait()
	local plrkey = "id_"..plr.UserId
	local save1 = plr.leaderstats.Time
	local save2 = plr.leaderstats.Level
	
	local GetSaved = ds:GetAsync(plrkey)
	if GetSaved then
		save1.Value = GetSaved[1]
		save2.Value = GetSaved[2]
	else
		local NumberForSaving = {save1.Value, save2.Value}
		ds:GetAsync(plrkey, NumberForSaving)
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	ds:SetAsync("id_"..plr.UserId, {plr.leaderstats.Time.Value, plr.leaderstats.Level.Value})
end)

leaderstats:

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local level = Instance.new("IntValue")
	level.Name = "Level"
	level.Value = 1
	level.Parent = leaderstats
	
	local totalTime = Instance.new("IntValue")
	totalTime.Name = "Time"
	totalTime.Value = 0
	totalTime.Parent = leaderstats
end)

local function addTime(player)
	while true do
		wait(1)
		player.leaderstats.Time.Value = player.leaderstats.Time.Value + 1
	end
end

game.Players.PlayerAdded:Connect(addTime)

I don’t see any errors there, Did you enabled “Allow API Services” On your game?

1 Like

um yeah

@MeCrunchAstroX I did check it as i said here

This is particularly helpful for me, put prints on absolutely everything that might be a problem, starting of functions, adding values, or before values, printing the datastore values, just do it all, which allows you to narrow down the issue. (remove them after tho)

1 Like

good idea, everything works besides the datastore stuff so that could work. see what a few more people say before i go through the trouble of it though.

use game:BindToClose() in the PlayerRemoving function datastores might not be saving because of the server closing too fast.

1 Like

I’m sorry, I must ask, where do I put that exactly? (sorry its late for me and I’m developing on spare energy)

game:BindToClose(function()
		for i,v in pairs(Players:GetPlayers()) do
			ds:SetAsync("id_"..v.UserId, {v.leaderstats.Time.Value, v.leaderstats.Level.Value})
		end
end)

I suppose its this havent tested it yet
add this as another function at the bottom

1 Like

Okay thanks, the code works perfectly now! This will be useful for keeping track of player’s in my game.

Sounds good, your code wasn’t working cause the server was closing / shutting down too fast and it was just stopping all the running scripts which causes datastores not saving.

2 Likes