Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

[UNANSWERED] Saving data every 5 seconds not working?

Hi guys :) I am trying to save leaderstats every 5 seconds! :) Any ideas why is this not working? (I am not great with datastores :/ ) Thanks in advance!

NOTE: Currently, I am saving when the player leaves the game, but it doesn't save if the game crashes. I need to get over this somehow, either by saving the data when it changes and when they leave or every 5 seconds. Thanks.

local ds = game:GetService("DataStoreService"):GetDataStore("stats")
lolz={"Escapes","Coins","Diamonds"}
game.Players.PlayerAdded:connect(function(plyr)
	local a=Instance.new("NumberValue")
	a.Parent=plyr
	a.Name="leaderstats"
	for i=1,#lolz do
		local stat=Instance.new("NumberValue")
		stat.Parent=a
		stat.Value=0
		stat.Name=lolz[i]
	end
local child=plyr.leaderstats:GetChildren()
	for i=1, #child do
		child[i].Value=ds:GetAsync(plyr.userId..child[i].Name)
	end
end)

while wait(5) do
local child=plyr.leaderstats:GetChildren()
	for i=1, #child do
		child[i].Value=ds:SetAsync(plyr.userId..child[i].Name,child[i].Value)
end

game.Players.PlayerRemoving:connect(function(plyr)
	local child=plyr.leaderstats:GetChildren()
	for i=1, #child do
		child[i].Value=ds:SetAsync(plyr.userId..child[i].Name,child[i].Value)
	end
	end)

6 comments

1

Saving every 5 seconds is an excessive amount of requests for ROBLOX.

0

^

0

Just save when someone leaves the game

0

^

1

@LordDragonZord but would that save the Player's Data if they crash though?

0

^^ It would not save if the game crashes, which is why I want to save it every 5 seconds or save it when the leaderstat changes!

1 answer

I prefer saving whenever the value changes, rather than every 5 seconds or when the player leaves. You'd only want to save when the player leaves if the value changes often (like if you needed to save altitude or something)

local ds = game:GetService("DataStoreService"):GetDataStore("stats")
lolz={"Escapes","Coins","Diamonds"}

game.Players.PlayerAdded:connect(function(plyr)
    local a=Instance.new("NumberValue")
    a.Parent=plyr
    a.Name="leaderstats"
    for i=1,#lolz do
        local stat=Instance.new("NumberValue")
        stat.Parent=a
        stat.Value=0
        stat.Name=lolz[i]
    end
   child=plyr.leaderstats:GetChildren() -- made it global for efficiency
    for i=1, #child do
        child[i].Value=ds:GetAsync(plyr.userId..child[i].Name)
    end
	for i,v in pairs (child) do
		v.Changed:connect (function ()
			ds:SetAsync (plyr.userId,v.Value)
		end)
	end
end)



game.Players.PlayerRemoving:connect(function(plyr)
    for i=1, #child do
        child[i].Value=ds:SetAsync(plyr.userId..child[i].Name,child[i].Value)
    end
    end)

1 comment

0

Thanks! But this didn't save the data :( Any ideas?

This discussion is preserved as it was. New answers, comments, and votes are closed.