I want to save the players data in a table and I want it to save when the player leaves the game (I will add save interval later). I set the table value to the value in the players leaderstats which I change when testing in studio. When I do so and print the value it says 0 instead of the number I changed the value to. I get no errors.
local DSS = game:GetService("DataStoreService")
local playerStore = DSS:GetDataStore("PlayerData")
local saveInterval = 10
local PlayerData = {Gold=0,Kills=0}
game:GetService("Players").PlayerAdded:Connect(function(plr)
local UID = plr.UserId
local stats = Instance.new("Folder")
stats.Parent = plr
stats.Name = "leaderstats"
local gold = Instance.new("IntValue")
gold.Parent = stats
gold.Name = "Gold"
local kills = Instance.new("IntValue")
kills.Parent = stats
kills.Name = "Kills"
local success, data = pcall(function()
return playerStore:GetAsync(UID) or PlayerData
end)
if success then
for k,v in next, data do
if k == "Gold" then
gold.Value = v
elseif k == "Kills" then
kills.Value = v
end
print(k,": ",v)
end
end
-- Save data when player leaves
game.Players.PlayerRemoving:Connect(function()
PlayerData.Gold = gold.Value
PlayerData.Kills = kills.Value
print(PlayerData.Gold) -- Prints 0?
print(PlayerData.Kills) -- Prints 0?
local success, err = pcall(function()
playerStore:SetAsync(UID,PlayerData)
end)
if not success then
warn("Database Error: "..err)
end
end)
end)

2 comments
Maybe if you wanted an answer, you wouldn't post the question again and delete the other question and delete drafts of answers on the other question.
that was a different script and I just remade it because of all the errors in the other script that I realized was made