Problem with Data Stores

Hi,
I have this script that handles data stores:

local DataStoreService = game:GetService("DataStoreService")
local datastore = DataStoreService:GetDataStore("datastore")

game:GetService("Players").PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Parent = player
	leaderstats.Name = "leaderstats"
	
	local OB = Instance.new("IntValue")
	OB.Parent = leaderstats
	OB.Name = "OB"
	
	local data0
	
	local success, err = pcall(function()
		data0 = datastore:GetAsync(player.UserId)
	end)
	
	OB.Value = data0 or 0
end)

game:GetService("Players").PlayerRemoving:Connect(function(player)
	local success, err = pcall(function()
		datastore:SetAsync(player.UserId, player.leaderstats["OB"].Value)
	end)
end)

And it’s not saving data sometimes, I don’t know what’s the problem. Also I have one unused data store and i don’t know how to remove it from my game. Can someone help?

1 Like

You can do a few things to fix this.

For one, I highly suggest using a datastore module such as DataStore2 or ProfileService

If you still want to use vanilla datastore you can try adding periodic saving events (like every 15 seconds it saves) to minimize data loss.

1 Like
local DataStoreService = game:GetService("DataStoreService")
local datastore = DataStoreService:GetDataStore("datastore")
local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Parent = player
	leaderstats.Name = "leaderstats"

	local OB = Instance.new("IntValue")
	OB.Parent = leaderstats
	OB.Name = "OB"

	local data0

	local success, err = pcall(function()
		data0 = datastore:GetAsync(player.UserId)
	end)

	OB.Value = data0 or 0
end)

Players.PlayerRemoving:Connect(function(player)
	local success, err = pcall(function()
		datastore:SetAsync(player.UserId, player.leaderstats["OB"].Value)
	end)
end)

game:BindToClose(function()
	for _, player in ipairs(Players:GetPlayers()) do
		local success, err = pcall(function()
			datastore:SetAsync(player.UserId, player.leaderstats["OB"].Value)
		end)
	end
end)

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

1 Like