I am trying to use a dataStore to save the player's cash but from some reason it does not work, does anyone see what the problem is? (the cash value is stored in an IntValue called "Cash" in leaderstats)
local DataStoreService = game:GetService("DataStoreService")
local cashStore = DataStoreService:GetDataStore("PlayerCash")
local Players = game:GetService("Players")
local AUTOSAVE_INTERVAL = 15
local function saveData(dataStoreKey, value)
local setSuccess, errorMessage = pcall(function()
cashStore:SetAsync(dataStoreKey, value)
end)
if not setSuccess then
warn(errorMessage)
end
end
local function onPlayerRemoving(player)
local playerUserID = player.UserId
local playerCash = player.leaderstats.Cash
if playerCash.Value then
saveData(playerUserID, playerCash.Value)
print("cash saved")
end
end
local function onPlayerAdded(player)
local playerUserID = player.UserId
local playerCash = player:WaitForChild("leaderstats"):WaitForChild("Cash")
local success, storedCash = pcall(function()
return cashStore:GetAsync(playerUserID)
end)
if success then
local currentCash = storedCash or 100
playerCash.Value = currentCash
end
coroutine.wrap(function()
while wait(AUTOSAVE_INTERVAL) do
if playerCash.Value then
saveData(playerUserID, playerCash.Value)
print("cash saved")
end
end
end)()
end
Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(onPlayerRemoving)

2 comments
Have you tested it outside of studio? And is there any errors in the output?
in studio i can just test it with play -> client right? there was an error about sending request to queue but that was fixed when i changed the AUTOSAVE_INTERVAL to 30