My Datastores Won't work

I’m trying to make a script that saves the leader Stats to a datastore. Yet it won’t output anything, and it won’t save either.

I have looked for solutions and I HAVE API ON.

Also here is the code.

Script 1, AKA “Leaderstats” As seen in the video.

game.Players.PlayerAdded:Connect(function(Player)
	local leaderstats = Instance.new("Folder", Player)
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = Player
	local Coins = Instance.new("IntValue", leaderstats)
	Coins.Value = 0
	Coins.Name = "Coins"
end)

Script 2, AKA “Script” As seen in the video.

local DataStoreService = game:GetService("DataStoreService")
local leaderstatsData = DataStoreService:GetDataStore("LeaderstatsData")

game.Players.PlayerAdded:Connect(function(player)
	local playerData = leaderstatsData:GetAsync(player.UserId)
	if not playerData then
		playerData = {
			Coins = 0
		}
		leaderstatsData:SetAsync(player.UserId, playerData)
	end

	player.leaderstats.Coins.Value = playerData.Coins
end)

game.Players.PlayerRemoving:Connect(function(player)
	local playerData = {
		Coins = player.leaderstats.Coins.Value
	}
	leaderstatsData:SetAsync(player.UserId, playerData)
end)

Please comment if you have any possible fixes.

4 Likes

Try adding a BindToClose function to save data on close.

local players = game:GetService("Players")
local runService = game:GetService("RunService")

--first, convert your saving function to something like this:

local function save(player)
    --saving code here
end


players.PlayerRemoving:Connect(save)

--then:
game:BindToClose(function()
    if #players:GetPlayers() <= 1 or runService:IsStudio() then task.wait(3) return nil end

    for _, player in ipairs(players:GetPlayers()) do
        save(player)
    end
    task.wait(5)
end)

Also, any request to the store should be wrapped in a pcall. They can sometimes error.

2 Likes