Why does my datastore not always save my data?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? That my datastore always works

  2. What is the issue? It does not always save

  3. What solutions have you tried so far? I tried looking but I did not find anything

Code:

local DataStore = game:GetService("DataStoreService")
local DeathStore = DataStore:GetDataStore("Deaths")
local RCStore = DataStore:GetDataStore("RC")

game.Players.PlayerAdded:Connect(function(player)

	local leaderstats = Instance.new("Model", player)
	leaderstats.Name = "leaderstats"

	local Deaths = Instance.new("IntValue", leaderstats)
	Deaths.Name = "Deaths"
	
	local RC = Instance.new("IntValue", leaderstats)
	RC.Name = "RC"

	pcall(function()
		local DeathValue = DeathStore:GetAsync(player.UserId)
		local RCValue = RCStore:GetAsync(player.UserId)
		
		player.CharacterAdded:Connect(function(character)
			character:WaitForChild("Humanoid").Died:Connect(function()
				Deaths.Value = Deaths.Value + 1
			end)
		end)
		
		if DeathValue then
			Deaths.Value = DeathValue
		else
			Deaths.Value = 0
		end

		if RCValue then
			RC.Value = RCValue
		else
			RC.Value = 0
		end
		
	end)
end)

game.Players.PlayerRemoving:Connect(function(player)
	pcall(function()
		if player:FindFirstChild("leaderstats") then
			if player.leaderstats:FindFirstChild("Deaths") and player.leaderstats.Deaths.Value then
				print("Saving...")
				DeathStore:SetAsync(player.UserId, player.leaderstats.Deaths.Value)
				print("Saved!")
			else
				print("Saving was not succesfull!")
			end
		end

		if player:FindFirstChild("leaderstats") then
			if player.leaderstats:FindFirstChild("RC") and player.leaderstats.RC.Value then
				RCStore:SetAsync(player.UserId, player.leaderstats.RC.Value)
			end
		end
	end)
end)

game:BindToClose(function()
	wait()
end)

If someone can tell me what the issue is please tell me! Also don’t hesitate to give me feedback!

2 Likes

Does this happen in Studio only or in game as well? I’ve noticed that testing in Studio has issues with Datastores consistently saving, but it’s never an issue in game.

thanks! I didn’t try that! But are there any improvements that I can make to the script?

1 Like

PlayerRemoving doesn’t always fire in studio, the local server which is created when testing in studio is sometimes closed/shut down before the PlayerRemoving event fires. If datastore saving is required in studio then you should use “BindToClose()”.

https://developer.roblox.com/en-us/api-reference/function/DataModel/BindToClose

2 Likes