ServerStorage does not save the player's balance in-game!

I want to make a game where the only currency that gets saved is your Bank Balance, however it does not save any data at all.

Check my script, tell me if anything is missing or misplaced.

local DataStoreService = game:GetService('DataStoreService')
local playerData = DataStoreService:GetDataStore('PlayerData')

local function onPlayerJoin(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = 'moneyAmounts'
	leaderstats.Parent = player
	
	local pocketMoney = Instance.new('IntValue')
	pocketMoney.Name = 'Pocket'
	pocketMoney.Parent = leaderstats
	pocketMoney.Value = 0
	
	local bankMoney = Instance.new('IntValue')
	bankMoney.Name = 'Bank'
	bankMoney.Parent = leaderstats
	
	local playerUserID = 'Player_'..player.UserId
	local data = playerData:GetAsync(playerUserID)
	
	if data then
		bankMoney.Value = data
	else
		bankMoney.Value = 0
	end
end

local function onPlayerExit(player)
	local success, err = pcall(function()
		local playerUserID = 'Player_'..player.UserId
		playerData:SetAsync(playerUserID, player.moneyAmounts.Bank.Value)
	end)
	if not success then
		warn('Could not save data!')
	end
end

game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)

Note: the script is under “ServerScriptService” as a “Script”

1 Like

Have you tried running the game in a live server?

what is that? Running the script on the game on the actual website?

Running the game from the website, data stores don’t typically work correctly in studio

1 Like

The game’s privacy is set to developer-only, but I dont know if it has to do with it.

It shouldn’t, the game should save data without issues. If it still doesn’t save, do you have Access to API Services enabled?

2 Likes

Try adding the :BindToClose function.

game:BindToClose(function()
    for i,player in pairs(game:GetService('Players'):GetPlayers()) do
        onPlayerExit(player)
    end
end
1 Like

Hi there, I threw your script into a place and found your code to be working perfectly as expected. Not sure what the issue is. I changed my Bank value to 3 and when I re-joined the value had saved.

BTW- you can enable DataStores in studio by going to Game Settings, Security and turning on “Enable studio access to API services”

3 Likes

Yes, the Access To API services is active

Go to https://www.roblox.com/create then click Manage My games then click on the game then press back in the top right, and it will bring you to your game page. You can then play the game from there even if the game is Private.

1 Like