- What do you want to achieve?
Save Player Cash Value on Exit.
- What is the issue? Include screenshots / videos if possible!
Followed Gnome Code’s tutorial word by word, but it seems I’ve encountered an error that he didn’t describe in the video. It seems that the function for PlayerRemoving works fine but the repeat loop isn’t running and the SetAsync isn’t telling me if the data was a success or not.
- What solutions have you tried so far? Did you look for solutions on the Developer Hub?
Made sure my code is exactly as written in the GnomeCode tutorial.
Here is the script
local Players = game:GetService("Players")
local DSS = game:GetService("DataStoreService")
local DataStore = DSS:GetDataStore("Money")
local sessionData = {}
function PlayerAdded(Player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
local cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Parent = leaderstats
local success = nil
local playerData = nil
local attempt = 1
repeat
success, playerData = pcall(function()
return DataStore:GetAsync(Player.UserId)
end)
attempt += 1
if not success then
warn(playerData)
task.wait(3)
end
until success or attempt == 5
if success then
if not playerData then
print("Assigning default data")
end
playerData = {
["Cash"] = 50,
}
end
sessionData[Player.UserId] = playerData
print("Connected Data",sessionData[Player.UserId])
else
warn("Unable to get data for", Player.Name)
Player:Kick("Unable to load data. Try again later.")
end
cash.Value = sessionData[Player.UserId].Cash
cash.Changed:Connect(function()
sessionData[Player.UserId].Cash = cash.Value
end)
leaderstats.Parent = Player
end
function PlayerRemoving(Player)
print("Player Leaving")
if sessionData[Player.UserId] then
local success = nil
local errorMsg = nil
local attempt = 1
print("Session Data Found")
repeat
success, errorMsg = pcall(function()
print("pcall running")
DataStore:SetAsync(Player.UserId, sessionData[Player.UserId])
end)
print("repeating")
attempt += 1
if not success then
warn(errorMsg)
task.wait(1)
end
until success or attempt == 5
if success then
print("Data saved for", Player.Name)
else
warn("Unable to save for", Player.Name)
end
end
end
Players.PlayerAdded:Connect(PlayerAdded)
Players.PlayerRemoving:Connect(PlayerRemoving)
function ServerShutdown()
print("Server shutting down.")
for i, player in ipairs(Players:GetPlayers()) do
task.spawn(function()
PlayerRemoving(Player)
end)
end
end
game:BindToClose(ServerShutdown)