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)
Maybe try testing this outside of ROBLOX studio, or going to the game settings and turning on API Services for Studio?
If you do not turn on API Services, and test in studio, it won't work.
Hello,
I haven't worked with DataStores in a while but try changing your local playerUserID = player.UserId
to local playerUserID = tostring(player.UserId)
. According to the documentation SetAsync wants a type string. If this is not the case please make sure to comment to I can make it right.
Well turns out the problem was caused because I was changing the cash value from a local script and not the server. the dataStore script itself has no problems. sorry for that I Guess