Data Not Saving

So I have this code in one of my Server-Side Scripts which is meant to save and load all data (points and wins):

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("Stats")

local players = game:GetService("Players")

local AUTO_SAVE = true			-- Make true to enable auto saving
local TIME_BETWEEN_SAVES = 60	-- In seconds (WARNING): Do not put this lower than 60 seconds
local SAFE_SAVE = true			-- Upon server shutdown, holds server open to save all data

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("Stats")
 
game.Players.PlayerAdded:connect(function(Player)
    local Leaderstats = Instance.new("Folder", Player)
    Leaderstats.Name = "leaderstats"

    local Points = Instance.new("IntValue", Leaderstats)
    Points.Name = "Points"
    Points.Value = 0

    local Wins = Instance.new("IntValue", Leaderstats)
    Wins.Name = "Wins"
    Wins.Value = 0
 
    local Data = DataStore:GetAsync(Player.UserId)
    if Data then
        Points.Value = Data.Points
        Wins.Value = Data.Wins
    end
end)
 
local function SaveData(Player)
    DataStore:SetAsync(Player.UserId, {
        ["Points"] = Player.leaderstats.Points.Value;
        ["Wins"] = Player.leaderstats.Wins.Value;
    })
end

if SAFE_SAVE then
	game.OnClose = function()
		for i, player in pairs(players:GetChildren()) do
			SaveData(player)
		end
		wait(1)
	end
end

while AUTO_SAVE do
	wait(TIME_BETWEEN_SAVES)
	for i, player in pairs(players:GetChildren()) do
		SaveData(player)
	end
end

However, when I leave the game, the data either doesn’t save or the data isn’t loading when I rejoin. I would appreciate it if someone could please help me out and possibly lead me to an answer. Thanks. :slight_smile:

Your dictionary must be set up this way in order to access it the way you did :

{
        Points = Player.leaderstats.Points.Value;
        Wins = Player.leaderstats.Wins.Value;
    }

And I would suggest adding a PlayerRemoving event, where you save the data for the player one more time when it leaves.

1 Like

Thanks for reminding me, it turns out that I didn’t have a player removing event to actually save the data even though I already made the function to save the data. (insert facepalm emoji here)

Use Players:GetPlayers() to get all players canonically, not ::GetChildren().

You also need to yield within the other loop here too, to prevent throttling

local TimeBetweenPlayerSaves = 5

while AUTO_SAVE do
	wait(TIME_BETWEEN_SAVES)
	for _, player in ipairs(players:GetPlayers()) do
		SaveData(player)
        wait(TimeBetweenPlayerSaves)
	end
end

game.OnClose is deprecated, use game:BindToClose()

Try saving OnPlayerRemoving appropriately.

1 Like

Thanks.
(30 characterssssssss)