I have tried to create a data storing system for currency in the game, but after following a tutorial, it doesn’t save the currency when I leave the game. The currency system otherwise works fine, and I want to note that I HAVE enabled studio access to API services in the game settings.
local DataStoreService = game:GetService("DataStoreService")
local dVersion = 1
local save = DataStoreService:GetDataStore("Currency "..dVersion)
game.Players.PlayerAdded:Connect(function(player)
local previousData = save:GetAsync(player.UserId)
local currency
if previousData ~= nil then
currency = previousData
else
currency = 0
save:SetAsync(player.UserId, 0)
end
local currencyValue = Instance.new("NumberValue", player)
currencyValue.Name = "Currency"
currencyValue.Value = currency
end)
game:BindToClose(function()
for i,player in pairs(game.Players:GetPlayers()) do
local value = player.Currency.Value
if value ~= nil then
save:SetAsync(player.UserId, value)
print("Data Saved")
end
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local value = player.Currency.Value
if value ~= nil then
save:SetAsync(player.UserId, value)
print("Data Saved")
end
end)
Are you testing the game in Studio? Usually, Studio does not fire :PlayerRemoving, which means that your data will not be saved in Studio (regardless of enabling access to API Services). Try testing the script in the published version of the game.
It also looks like your script is saving the value only if the value is not equal to nil. This means that if data was previously saved in the DataStore used, it will not work (unless the value is nil)
Try removing the if statement surrounding the SetAsync function.
I believe it’s because the server is closing before it can work through all the data. Try putting game:BindToClose(function() wait(5) end)
at the very end of your script outside of the PlayerRemoving