I have a simple Data Store script that is supposed to save player stats. The problem is that the script runs every-line, (from what I can tell) but nothing is being saved. Everything just gets set to the default value 10.
I have been tinkering for a while, placing print() functions in every place where I either deal with the data being saved, or the saving itself. Everything came out fine. Even in the table that is being saved the data is showing what is supposed to be saved. I do have Data Stores enabled, so that’s not the problem. There is also no errors or warnings in the output. Here’s the code since I am probably just not seeing something:
local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetDataStore("DataStoreV0.01")
-- loaded = true if the data has been loaded
local loaded = false
local tries = 3
local function Set(plr)
-- Only runs when data has been loaded
if loaded then
local key = "key-" .. plr.UserId
local data = {
["cash"] = plr.leaderstats.Cash.Value
};
local count = 0
local success, err
repeat
success, err = pcall(function()
dataStore:SetAsync(key, data)
end)
count = count + 1
wait(0.5)
until count >= tries or success
if not success then
warn("Failed to serialize data. Error code: " .. tostring(err))
return
end
end
end
local function Get(plr)
local key = "key-" .. plr.UserId
local count = 0
local success, err
local serialized
-- Gets the data
repeat
success, err = pcall(function()
serialized = dataStore:GetAsync(key)
end)
count = count + 1
wait(0.5)
until count >= tries or success
if not success then
warn("Failed to read data. Error code: " .. tostring(err))
return
end
if serialized then
return serialized
else
return {["cash"] = 10}
end
end
local function CreateLeaderstats(plr)
-- Creates a new leaderboard
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = plr
local cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Parent = leaderstats
cash.Value = Get(plr).cash -- should set the value to the saved value
loaded = true -- set to true since data has been loaded
end
-- calls
players.PlayerAdded:Connect(CreateLeaderstats)
players.PlayerRemoving:Connect(Set)
The script is not disabled and it’s location is ServerScriptService. This is not a Roblox issue since another game I am working on, (using a slightly different and more advanced system) works fine. I just can’t see the problem.
Thanks!