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)
on line 31 - 33, there is no need to call the OnPlayerAdded()
function for the players. The Players.PlayerAdded
does everything required for it to work correctly. And I'm sure that's why the datastore doesn't work correctly.
So, what you need to do is just remove loop function at line 31, 32 and 33. It will be working fine then.