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

Why isn't this DataStore script working correctly?

Asked by 6 years ago

I'm trying to get my DataStore script to automatically detect all the stats in the player's stats folder, as there are many, and save/load them all accordingly. For some reason however, it's either not saving correctly or not loading correctly. When I run the game, set the values of the stats, then leave, when I rejoin all of them are back to their default values instead of the ones that should have been saved.

local dataStore = game:GetService("DataStoreService")
local players = game:GetService("Players")

local statsStore = dataStore:GetDataStore("StatsStore")

function playerAdded(player)
    local playerGui = player:WaitForChild("PlayerGui")
    local statsGui = playerGui:WaitForChild("StatsGui")
    local playerStats = statsGui:WaitForChild("PlayerStats") --the folder where all the player's stat values are stored

    local key = ("player_"..player.UserId)

    local savedStats = statsStore:GetAsync(key)

    local statsToSave = {}

    for _, playerStat in pairs(playerStats:GetChildren()) do
        statsToSave[playerStat.Name] = playerStat.Value
    end

    if savedStats then
        for statName, stat in pairs(savedStats) do
            local playerStat = playerStats:FindFirstChild(statName)
            if playerStat then
                playerStat.Value = stat
            end
        end
    else
        statsStore:SetAsync(key, statsToSave)
    end
end

function playerRemoved(player)
    local playerGui = player:WaitForChild("PlayerGui")
    local statsGui = playerGui:WaitForChild("StatsGui")
    local playerStats = statsGui:WaitForChild("PlayerStats")

    local key = ("player_"..player.UserId)

    local statsToSave = {}

    for _, playerStat in pairs(playerStats:GetChildren()) do
        statsToSave[playerStat.Name] = playerStat.Value
    end

    statsStore:SetAsync(key, statsToSave)
end

players.PlayerAdded:connect(playerAdded)
players.PlayerRemoving:connect(playerRemoved)
0
You should create the stats and load them in the same script. FindFirstChild on line 23 can be nil and wipe data. User#5423 17 — 6y
0
I see, I'll try this. crabbyninja 58 — 6y

Answer this question