Could anyone help me re-code for efficiency this? Because sometimes it does not load or save properly and i feel like I messed up on it (i think that why). If Anyone could help me?
Game.Players.PlayerAdded:connect(function(Player) Player:WaitForChild("leaderstats") wait(1/30) local DataStore = Game:GetService("DataStoreService"):GetDataStore(Player.Name.."Stats") for i,v in pairs(Player.leaderstats:GetChildren()) do v.Value = DataStore:GetAsync(v.Name) DataStore:UpdateAsync(v.Name, function(Current) local Base = Current or 0 return Base end) end end) Game.Players.PlayerRemoving:connect(function(Player) if Player:FindFirstChild("leaderstats") == nil then return end local DataStore = Game:GetService("DataStoreService"):GetDataStore(Player.Name.."Stats") for i,v in pairs(Player.leaderstats:GetChildren()) do DataStore:SetAsync(v.Name, v.Value) DataStore:UpdateAsync(v.Name, function(Current) local Base = Current or 0 return Base end) end end)
local datastore = game:GetService("DataStoreService"):GetDataStore("Stats") game.Players.PlayerRemoving:connect(function(player) player:WaitForDataReady() local key = "user_" .. player.userId datastore:UpdateAsync(key, function(oldValue) -- We don't wanna use SetAsync we don't want any chnaces of data lose anyway local a = player:WaitForChild("leaderstats"):GetChildren() for i= 1,#a do -- For every number of children DataStore:SetAsync(a[i].Name, a[i].Value) -- Saves all children values end end)
So first of all, when the player removes, it Saves it username and stats, I added comments on some. Now when player joins :P
local datastore2 = game:GetService("DataStoreService"):GetDataStore("Stats") game.Players.PlayerAdded:connect(player) wait(20) -- We don't want to reach maximum request for datastore so the player waits 20 seconds before loading player:WaitForDataReady() -- Waiting for player local key = "user_" .. player.userId if DataStore:GetAsync(key) ~= nil then -- If they is not equal to nil it will get and load stats local a2 = newplayer:WaitForChild("leaderstats"):GetChildren() -- Make sure that the script doesn't load before leader stats for i = 1, #a2 do -- Same as old one datastore2:GetAsync(a2[i].Name) -- Brackets for as2[i] means for every one or is equal to i end end end)
You can put both scripts in the same script, This should work. Good Luck HexC3D