Hello,
I made an inventory system that receives your tools from a specific folder, which is located inside the player. The issue is, sometimes when I join my game for the sake of testing, I don’t receive my tools. The weird thing is, I have a print statement that prints the user’s inventory. The print statement always seems to print the user’s inventory flawlessly, however sometimes user doesn’t receive his/her items, which is a huge problem. Any suggestions?
Code:
local DataStore = game:GetService("DataStoreService")
local InventoryDS = DataStore:GetDataStore("InventoryDS")
local ToolsFolder = game.ServerStorage.Tools
--When the player is added
game.Players.PlayerAdded:Connect(function(player)
local InvFolder = Instance.new("Folder")
InvFolder.Name = "InvFolder"
InvFolder.Parent = player
local success, errormessage = pcall(function()
inventory = InventoryDS:GetAsync(player.UserId) or {}
for i,v in pairs(inventory) do
if ToolsFolder:FindFirstChild(v) then
ToolsFolder[v]:Clone().Parent = player.Backpack
ToolsFolder[v]:Clone().Parent = player.InvFolder
end
end
end)
if success then
print(player.Name.." - Data received upon join.[INV]")
print(inventory)
else
print(player.Name.." - Data couldn't be received upon join.[INV]")
warn(errormessage)
end
end)
--When player is removed
game.Players.PlayerRemoving:Connect(function(player)
local inventory = {}
for i,v in pairs(player.InvFolder:GetChildren()) do
table.insert(inventory, v.Name)
end
local success, errormessage = pcall(function()
InventoryDS:UpdateAsync(player.UserId, function(new)
return inventory
end)
end)
if success then
print(player.Name.." - Data saved upon removal[INV]")
else
print(player.Name.." - Data couldn't be saved upon removal.[INV]")
warn(errormessage)
end
end)
--When server shutdowns
game:BindToClose(function()
local players = game.Players:GetPlayers()
local inventory = {}
for i = 1, #players do
for i, v in pairs(players[i].InvFolder:GetChildren()) do
table.insert(inventory, v.Name)
end
local success, errormessage = pcall(function()
InventoryDS:UpdateAsync(players[i].UserId, function(new)
return inventory
end)
end)
wait(6)
if success then
print(players[i].Name.." - Data saved upon removal[INV]")
else
print(players[i].Name.." - Data couldn't be saved upon removal.[INV]")
warn(errormessage)
end
end
end)