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)
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)