local datastorageservice = game:GetService("DataStoreService")
local toolsData = datastorageservice:GetDataStore("ToolsData")
game.Players.PlayerAdded:Connect(function(player) -- load data
local playerBackpack = Instance.new("Folder")
playerBackpack.Name = player.Name .."BackPack"
playerBackpack.Parent = game:GetService("ServerStorage").BackPacks
local data
local success, errormsg = pcall(function()
data = toolsData:GetAsync(player.UserId)
end)
if success then
if data then
for i,Tools in pairs(playerBackpack:GetChildren()) do
Tools:Clone()
Tools.Parent = player.Backpack
end
end
end
end)
game.Players.PlayerRemoving:Connect(function(player) -- save data
local Tools = {}
for i,Tool in pairs(player.Backpack:GetChildren()) do
if Tool:IsA("Tool") then
table.insert(Tools,Tool.Name)
end
end
toolsData:SetAsync(player.UserId,Tools)
end)
i dont know how data storages really work so ima head off and watch anime pce pce
When you’re looping through the items inside “playerBackpack” on line 17, there are not any items inside this folder. Since this does not appear to be in use, it is not necessary to have it.
When you’re saving the data, you save it as a table containing all the tool names, so you can simply load these items from the table. You should also use pcall() when saving data to catch errors when saving. The example below will save and load the tools when a player leaves/joins.
local DataStoreService = game:GetService("DataStoreService")
local toolsData = DataStoreService:GetDataStore("ToolsData")
---> load data when player joins
game.Players.PlayerAdded:Connect(function(player)
local data
local success, erromsg = pcall(function()
data = toolsData:GetAsync(player.UserId)
end)
if success then
if data then
for i,tool in pairs(data) do
-- Since you're saving the tool names to the table, you can search for them in a certain place.
local toolClone = game.ServerStorage[tool]:Clone()-- Change to where you are storing the tools in the game.
toolClone.Parent = player.Backpack
end
end
end
end)
---> save data when player leaves
game.Players.PlayerRemoving:Connect(function(player)
local Tools = {}
for i,tool in pairs(player.Backpack:GetChildren()) do
if tool:IsA("Tool") then
table.insert(Tools,tool.Name)
end
end
local success, errormsg = pcall(function()
toolsData:SetAsync(player.UserId,Tools)
end)
if not success then
warn("Failed to save tools data - "..errormsg)
end
end)
You can view more information about how to use DataStores here.
game.Players.PlayerAdded:Connect(function(player) – load data
local data
local success, erromsg = pcall(function()
data = toolsData:GetAsync(player.UserId)
end)
if success then
if data then
for i,tool in pairs(data) do
local toolClone = game:GetService("ServerStorage").Tools:FindFirstChild(tool):Clone()
toolClone.Parent = player.Backpack
end
end
end