Inventory Datastore

Hello I am trying to find the best way to save the player’s inventory when the player leaves, like a datastore.

Basically I want the position of gui elements to have the same contents and be in the same position they were in before I left, how do I achieve this?

image

Use LayoutOrder.

local num = 0
for _,obj in pairs(FRAME:GetChildren()) do
if obj:IsA('GuiObject') then
obj.LayoutOrder = num + 1
num += 1
end
end

Not entirely sure if it’ll work but it should

edit: You then store the LayoutOrder in the datastore, multiple examples can be:

[1] = {data}
[2] = {data}

---
{1, {data}}
{2, {data}}

and so on

If your primary concern is with GUI positioning, just add a key that has a sort order similar to that found UIGridStyleLayout.

This seems like a solution. Can you explain how this works in more detail? thanks

LayoutOrder starts from 0 and goes to … whatever number you want it to end up at.

It’s super helpful and I didn’t know that it worked well until a few years into my developing career.

Ultimately, you store the LayoutOrder number (which is “1” in my example) and then transfer that data to the client so that it can create a good UI for the player

In it’s most elementary form, your code could look something like this:

-- Hypothetical data structure
local inventory ={
	Item1 = {
		
		Layout = 1
	};
	Item2 = {
		
		Layout = 3
	};
	
	Item3 = {
		
		LayoutOrder = 2
	}
}

-- Found in  Local Script (GUI handling)
for i, v in pairs(inventory) do
	
	-- Apply sort order here onto GUI object
	
end

LayoutOrder utilises a low-to-high sort - the lowest number will appear first. In the above code, the GUI would hypothetically display Item1, Item3 and then Item2. It could be of use keeping an array to track the Layout Order.

local tracking = {
"Item1",
"Item3",
"Item2"
}

By using this array you could match the LayoutOrder to the Item’s index.

1 Like

This is very useful, also do you know how to track the items? For example if I pick up a new item how do I add this to the table.

You should just be able to use table.insert

1 Like

also how do I make a datastore for a table?

This should be what you’re looking for

2 Likes

Thank you this is very helpful

1 Like