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

My DataStore saves everyones data and adds it together. How can I fix this?

Asked by 6 years ago
Edited 6 years ago

If I have a value of 100 in my PlayerStats and I leave the game and a totally new player that's never played the game before joins they will also have a value of 100 in their PlayerStats. This happens with all vlaues saved in the DataStore. I'm new at creating DataStores can someone tell me what I'm doing wrong?

DataStore:

local DataStore = game:GetService("DataStoreService"):GetDataStore("Stats")

game.Players.PlayerRemoving:connect(function(Player)
    Player:WaitForDataReady()
local Stats = Player:FindFirstChild("PlayerStats"):GetChildren()
    for i = 1, #Stats do
        DataStore:SetAsync(Stats[i].Name,Stats[i].Value)
    end
end)

game.Players.PlayerAdded:connect(function(Player)
    Player:WaitForDataReady()
local Stats2 = Player:FindFirstChild("PlayerStats"):GetChildren()
    for i = 1, #Stats2 do
        Stats2[i].Value = DataStore:GetAsync(Stats2[i].Name)
    end
end)

What the DataStore saves:

local Stats = {"Kills", "zCoins", "Points"}

local function Create(User)
    local StatsFolder = Instance.new("Folder",User)
    StatsFolder.Name = "PlayerStats"
    for i = 1,#Stats do
        Instance.new("IntValue",StatsFolder).Name = Stats[i]
    end
end

game.Players.PlayerAdded:connect(function(Player)
    Create(Player)
end)

1 answer

Log in to vote
0
Answered by 6 years ago

Unlike its predecessor, DataStore saves in a way that any player can access it, which is causing the problem here.

The DataStore "Stats" that you've defined is a table. Not in the Lua sense, but DataStores are tables, with a key and a value.

For each player to have their own unique DataStore in this way, you will need a unique key for each player. Luckily, ROBLOX have the UserID for that.

You can create a dictionary from Stats, by doing something like:

local StatsDict = {}
for i = 1, #Stats do
    StatsDict[Stats[i].Name] = Stats[i].Value
end

And then to save it to DataStore under the player do DataStore:SetAsync(tostring(Player.UserId), StatsDict).

When you get the DataStore, you will get the dictionary containing the names and values of each stat, which you can use to set the stats.

Alternatively, you can set the DataStore name to be the individual's UserID, but that isn't really recommended.

Ad

Answer this question