Search code examples
luainventoryroblox

How do i make efficient slots in an inventory?


I'm making a game, and I've gotten to the point where an inventory is needed. I mean a custom one. I have the gui made and all the other stuff working, but I can't find an efficient way to make the slots(for tools) to slide up. It's like this.

Ok, so i have two items in my inventory. One at the very top, one directly below the first. I click the top one(to take it out) and the second one just stays there being awkward a little ways down from the very top.

--the only way i know of doing this is with a lot of if/elseif's

if not gui.Position == UDim2.new(0,13,0,123) then
gui2.Position = UDim2.new(0,13,0,123)
end

something like that,but what if i had 10 slots? 20? More if's is all i can think of. So, do you know a way to make this efficient?

So, according to the answer here, this would be the way to do it:

t = script.Parent
gui = script.Parent.Parent

t.MouseButton1Click:connect(function()
    t.Position = t.Position + UDim2.new(0,1,0,0)
    gui.w1.Position = t.Position + UDim2.new(0,0, 0, t.Size.Y.Offset)
    gui.w2.Position = gui.w1.Position + UDim2.new(0,0, 0, t.Size.Y.Offset)
    gui.w3.Position = gui.w2.Position + UDim2.new(0,0, 0, t.Size.Y.Offset)
    gui.w4.Position = gui.w3.Position + UDim2.new(0, 0, 0, t.Size.Y.Offset)
    gui.w5.Position = gui.w4.Position + UDim2.new(0, 0, 0,t.Size.Y.Offset)
end)

is this what you were meaning, or did i miss the point?


Solution

  • First off, out of pure luck, I recognize your code as ROBLOX Lua. In the future when asking questions on this site, you should specify that you are coding in ROBLOX Lua, because the API is very unique and most people here don't know about ROBLOX.

    If I understand your question correctly, you're trying to make a GUI inventory slots, right? I'm also going to assume you are using a Frame as the GUI object, since you didn't specify.

    My suggestion is to separate them based on their size. A UDim2 value has two pairs of numbers. The first number in each pair is called scale, and it's for positioning based on relative screen size. The second is called offset, and it's for positioning based on an amount of pixels. You should generally only use one or the other, which you are already doing, so that's good.

    With that in mind, you can create a new slot that automatically positions itself beside another. Something like this:

    newGui.Position = oldGui.Position + UDim2.new(0, oldGui.Size.XOffset, 0, 0)