You can't save instances in DataStores, but what you can do is save them in an array or dictionary.
Saving:
As mentioned before, DataStores can't save instances but you can save their names or values in an array or dictionary. You can loop through all instances in the player's inventory, and add the name of that instance to the table, then proceed with saving
local dss = game:GetService('DataStoreService'):GetDataStore('PlayerData')
game.Players.ChildRemoved:Connect(function(player)
local tbl = {}
local success, message = pcall(function()
for _,v in pairs(player.Inventory:GetChildren()) do
tbl[#tbl+1] = v.Name
end
dss:SetAsync(player.UserId, tbl)
end)
if success then
print("Saved "..player.Name.."'s data")
else
print('Failed to save data: '..message)
end
end)
Retrieving:
To retrieve the data, we'll have to use GetAsync. When the player joins, we'll call GetAsync if they have any saved data, if they do then we'll loop through the table and insert the instances needed and change its name and or value, else the player has no saved data, and we'll use a blank table.
game.Players.ChildAdded:Connect(function(player)
local data = dss:GetAsync(player.UserId) or {}
local inventory = Instance.new('Folder')
inventory.Name = 'Inventory'
inventory.Parent = player
for _, v in pairs(data) do
local value = Instance.new('StringValue')
value.Name = v
value.Parent = inventory
end
end)
1 comment
Don't do Instance.new(instance, parent), the 2nd parameter is deprecated and is less efficient than doing Inventory = Instance.new("Folder"); Inventory.Parent = player