It doesn’t seem to be saving. I’m not sure thought whether it’s the loading or saving. I’ve tried using pcalls, and I think it’s the saving.
I checked around the Devforum, and I tried solutions, but it’s not working, and I don’t know why.
Access to API is enabled.
local GiveMoney = 10
local DSS = game:GetService("DataStoreService")
local MoneyDataStore = DSS:GetDataStore("MoneyDataStore")
game.Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = plr
Cash = Instance.new("IntValue")
Cash.Name = "Cash"
Cash.Parent = leaderstats
local Data = MoneyDataStore:GetAsync(tostring(plr.UserId))
if Data then
Cash.Value = Data
else
Cash.Value = 0
end
end)
while true do
wait(10)
GiveMoney = GiveMoney + 1
Cash.Value = Cash.Value + 10
end
local function SaveData(plr)
MoneyDataStore:SetAsync(tostring(plr.UserId), Cash.Value)
end
game.Players.PlayerRemoving:Connect(SaveData)
You have a while loop right before the player remove event and save function. A while loop will basically yield/pause the thread unless broken out of (forcefully or if the condition is met). Best practice would be to either wrap it in a coroutine or keep it at the bottom of your thread.
Because you’re not updating the cash value. The loop is outside the scope and therefore “cash” doesn’t exist. Unless you made a typo and didn’t include the cash variable.
To confirm its the datastore. Go into a play test (make sure access to api is enabled) → switch to server view → give your self a random amount of cash → than in server view go to players and delete your player (this will basically work the same as if you left but it will keep the server running). Once thats done just exit the play test and retry to see if it saved.
Also remove the setAsync inside the playerAdded connection as its useless.
Basically you created and stored the variable Cash inside the playerAdded function. The while loop isn’t inside the scope and cannot actually see it. So just do the below:
Change this:
Cash = Instance.new("IntValue")
to
local Cash = Instance.new("IntValue")
For your loop’ we can just loop through all players to give them 10 coins.
while true do
wait(10)
for Index, Player in ipairs(game:GetService("Players"):GetPlayers())do
Player.leaderstats.Cash.Value = Player.leaderstats.Cash.Value + 10
end
end
And last just remove this line from the player added connection as you don’t need it:
Could you check if the values getting updated in the loop? Note that sometimes studio test plays shutdown before anything can actually save. So just go to server view and delete thr player to mimic a player leaving