My goal is that every player can have propertys ( diffrent buildings ) and inside these buildings they can store cars ( which also get saved ).
So how would I actually get that structure inside a folder and read from that to load it?
I’ve tried this but It’s not really doing what I want.
function saveInventory(Player)
local inv = {}
local int = 0
for i, v in pairs(game.Players:FindFirstChild(Player.Name).DataStore.Properties:GetDescendants()) do
if v.Parent.Name == "Properties" then
int = int + 1
table.insert(inv,v.Name)
for i,b in pairs(v:GetDescendants()) do
if b:IsA("StringValue") then
table.insert(inv,int,b.Name)
print(b.Name.." is a car in "..v.Name)
end
end
end
end
pcall(function()
DataStore:SetAsync(Player.UserId,HttpService:JSONEncode(inv))
end)
end
So after that code I thought okey it’s in the table like this
if newData then
print("Found data")
newData = HttpService:JSONDecode(newData)
for i,v in pairs(newData) do
local prop = Instance.new("StringValue")
prop.Parent = game.Players[player.Name].DataStore.Properties
prop.Name = v
local fold = Instance.new("Folder")
fold.Parent = prop
fold.Name = "StoredCars"
end
end
But I don’t know how to like get the right stuff out of it.
Any help is appreciated!
Your table is only 1 layer deep yet you’re expecting several layers. I’ve edited your saveInventory function to nest the stored cars within the property.
Additionally, you don’t need to encode and decode tables - it just complicates things and doesn’t save you any space. Save the table directly to the datastore.
function saveInventory(Player)
local inv = {}
for _, c in ipairs(Player.DataStore.Properties:GetChildren()) do
inv[c.Name] = {}
for _, d in ipairs(c.StoredCars:GetChildren()) do
if d:IsA("StringValue") then
table.insert(inv[ c.Name ], d.Name)
print(d.Name.." is a car in "..c.Name)
end
end
end
pcall(function()
DataStore:SetAsync(Player.UserId, inv)
end)
end
And then to load it back:
if newData then
print("Found data")
for property, cars in pairs(newData) do
local prop = Instance.new("StringValue")
prop.Name = property
local fold = Instance.new("Folder")
fold.Name = "StoredCars"
fold.Parent = prop
for _, car in ipairs(cars) do
local val = Instance.new("StringValue")
val.Name = car
val.Parent = fold
end
-- Parent after all properties and children have been added for performance reasons.
prop.Parent = Player.DataStore.Properties
end
end
Did you store it encoded again? You’ll need a new key if you’ve not already changed it as the data was in the wrong format and as a string before from your previous attempts.