I have been working on a currency system for my game for a little bit trying to work out the issues. I finally got the save part of the script to work but now the load data part does not work correctly. When I run my test I start the game and press a button that takes away 100 Cash from the player, then I exit the game. The save print says the correct number in the console, however, when I join the game again the Cash value starts back at what it was the previous test. What am I missing here? (New to Lua, CompSci student)
local Players = game:GetService("Players")
local CashDataStore = game:GetService("DataStoreService"):GetDataStore("Cash")
local STARTING_CASH = 100
local function onPlayerAdded(player)
local playerKey = "Player_" .. player.UserId
print("User ".. player.UserId.. " Joined")
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local Cash = Instance.new("IntValue", leaderstats)
Cash.Name = "Cash"
local myCash
local success, err = pcall(function()
myCash = CashDataStore:GetAsync(playerKey) or STARTING_CASH
end)
if success then
Cash.Value = myCash
print("loading "..myCash)
else
print("failed to retrieve data")
end
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
local function onPlayerLeft(player)
local playerKey = "Player_"..player.UserId
local savedCash = player.leaderstats.Cash.Value
print("User has "..savedCash.." in the bank")
savedCash = CashDataStore:SetAsync(playerKey, savedCash)
print("User "..player.UserId.." disconnected")
end
Players.PlayerRemoving:Connect(onPlayerLeft)

5 comments
are there any errors on the output?
There are no errors on the output. The last thing in the console is the last print that the save does.
It will depend, do you change your cash value on the client, because that doesn't replicate on the server. Try changing it on the server and see if it works
that could very well be the issue. I will check.
I am using remote events to change the values server side. do I need to define the datastore in the RemoteEvents script as well?