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

local ReplicatedStorage = game:GetService('ReplicatedStorage')
local Shop = ReplicatedStorage:WaitForChild('ShopItems')

local function onPlayerJoin(player)  -- Runs when players join

    local playerUserId = "Player_" .. player.UserId  --Gets player ID
    local data = playerData:GetAsync(playerUserId)  --Checks if player has stored data
	if data then
		print('here')
		for k, j in pairs(data) do
			print('loop')
			print(j)
			local giveTool = Shop:WaitForChild(j):Clone()
			giveTool.Parent = player:WaitForChild('Backpack')
		end
	else
		print('error')
        return
    end
end

local function onPlayerExit(player)  --Runs when players exit
	 
	local tool_table = {}
	
	for _, item in pairs(player.Backpack:GetChildren()) do
		print(item.Name)
		table.insert(tool_table, item.Name)
	end
	
	local success, err = pcall(function()
		print('Saved')
        local playerUserId = "Player_" .. player.UserId
        playerData:SetAsync(playerUserId, tool_table) --Saves player data
    end)

    if not success then
        warn('Could not save data!')
    end
end

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

4 comments

0

it's because the game shutdowns before "PlayerRemoving" finishes saving the data, see https://devforum.roblox.com/t/how-to-properly-save-player-data-in-data-stores-upon-server-close/313218

0

i will put a new line?

0

yeah you can put 46 new lines, main part of it is BindToClose in which you should save data of all players in the game, here is an example: https://gist.github.com/kirdaaa/5356b9f8c1b4647fd73ea4a1e346a0ea

0

i will use that? krida?