Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why does this Data Store script not work all the time?

Asked by 8 years ago

This script is in ServerScriptService (not local script). Before I released the game it tested perfectly. After a month and a lot of people playing, I now have some players telling me their leaderstats reset to zero when rejoining the game. I have no clue whats wrong?

Please help, I would be so very thankful.

Thanks so much! Tobycats

DataStore = game:GetService("DataStoreService"):GetDataStore("StatsService")

game.Players.PlayerAdded:connect(function(player)
    repeat wait() until player:FindFirstChild("leaderstats") 
    repeat wait() until player.leaderstats:FindFirstChild("Rank") 
    repeat wait() until player.leaderstats:FindFirstChild("XP") 
    repeat wait() until player.leaderstats:FindFirstChild("Kills") 

    local PlrsRank = DataStore:GetAsync(player.Name .. "_Rank") 
    local PlrsXP = DataStore:GetAsync(player.Name .. "_XP") 
    local PlrsKills = DataStore:GetAsync(player.Name .. "_Kills")

        if PlrsRank ~= nil then 
        player.leaderstats.Rank.Value = PlrsRank
        player.leaderstats.XP.Value = PlrsXP 
        player.leaderstats.Kills.Value = PlrsKills
     end
end)

game.Players.PlayerRemoving:connect(function(player) 
      if player:FindFirstChild("leaderstats") then 
        if player.leaderstats:FindFirstChild("Rank") then 
        DataStore:SetAsync(player.Name .. "_Rank", player.leaderstats.Rank.Value) 
        end

     if player.leaderstats:FindFirstChild("XP") then 
        DataStore:SetAsync(player.Name .. "_XP", player.leaderstats.XP.Value)
        end

     if player.leaderstats:FindFirstChild("Kills") then 
        DataStore:SetAsync(player.Name .. "_Kills", player.leaderstats.Kills.Value)
        end
     end
  end)`

1 answer

Log in to vote
0
Answered by 8 years ago

This is because the :SetAsync() is for immutable variables. For mutable values, values that will always change like statistics, the :UpdateAsync() method is a much better approach since multiple servers may be accessing the data.

Even though you called the method, the actual saving may be done minutes ahead of time due to lag in the server or the request limit.

:UpdateAsync() accounts for the old value of the value being changed, ensuring that it's what it was prior and is not being interrupted/change by anything else during the save. :SetAsync() does not account for this.

0
A general rule of thumb is to use :SetAsync() for immutable variables or data that once set - will never change. :UpdateAsync() is for mutable variables - variables that change frequently or can change. AbstractCode 16 — 8y
Ad

Answer this question