Hello, So I'm making a game and my cash saving doesn't work. I searched on the internet but to no avail so I came here.
My code (In a server script in ServerScriptService)
local DataStoreService = game:GetService("DataStoreService") local SaveDataStore = DataStoreService:GetDataStore("Save") game.Players.PlayerAdded:Connect(function(player) local Cash = Instance.new("IntValue", player) Cash.Name = "Cash" Cash.Value = SaveDataStore:GetAsync(player.UserId) or 0 end) game.Players.PlayerRemoving:Connect(function(player) if player:FindFirstChild("TagValue") then player.Cash.Value -= 50 end SaveDataStore:GetAsync(player.UserId, player.Cash.Value) end)
Okay so this data store script is pretty faulty:
This is how an actual data store setup would look like: (I didn't test it so tell me if something doesn't work)
local DataStoreService = game:GetService("DataStoreService") local CashDS = DataStoreService:GetDataStore("Cash") local RS = game:GetService("RunService") game.Players.PlayerAdded:Connect(function(plr) local ls = Instance.new("Folder") ls.Name = "leaderstats" ls.Parent = plr local Cash = Instance.new("IntValue") Cash.Name = "Cash" Cash.Parent = ls Cash.Value = 0 local data local g, err = pcall(function() data = CashDS:GetAsync("cash_"..plr.UserId) end) if not g then warn(err) else if data ~= nil then Cash.Value = data end end end) game:BindToClose(function() if RS:IsStudio() then return end local plrs = game.Players:GetPlayers() for _, plr in pairs(plrs) do local data = plr.leaderstats.Cash.Value if plr:FindFirstChild("TagValue") then data -= 50 end if data then local g, err = pcall(function() CashDS:UpdateAsync("cash_"..plr.UserId, function(old) local new = old or 0 new = data return new end) end) if not g then warn(err) end end end end) game.Players.PlayerRemoving:Connect(function(plr) local data = plr.leaderstats.Cash.Value if plr:FindFirstChild("TagValue") then data -= 50 end if data then local g, err = pcall(function() CashDS:UpdateAsync("cash_"..plr.UserId, function(old) local new = old or 0 new = data return new end) end) if not g then warn(err) end end end)
I recommend you read up on https://developer.roblox.com/en-us/articles/Data-store as well as you can ask me any questions you could have.