I'm trying to make my own inventory, so far so good. But to me, this script that updates the inventory seems very long, and inefficient. Is there any way I can improve it?
local plr = game.Players.LocalPlayer local buttons = script.Parent.IFrame:GetChildren() local items = plr.Backpack:GetChildren() local iframe = script.Parent.IFrame function updateinven() for i = 1,#items do if #items == 1 then iframe.Button1.Visible = true iframe.Button1.ItemName.Value = items[1].Name iframe.Button1.Text = items[1].Name elseif #items == 2 then iframe.Button1.Visible = true iframe.Button1.ItemName.Value = items[1].Name iframe.Button1.Text = items[1].Name iframe.Button2.Visible = true iframe.Button2.ItemName.Value = items[2].Name iframe.Button2.Text = items[2].Name elseif #items == 3 then iframe.Button1.Visible = true iframe.Button1.ItemName.Value = items[1].Name iframe.Button1.Text = items[1].Name iframe.Button2.Visible = true iframe.Button2.ItemName.Value = items[2].Name iframe.Button2.Text = items[2].Name iframe.Button3.Visible = true iframe.Button3.ItemName.Value = items[3].Name iframe.Button3.Text = items[3].Name elseif #items == 4 then iframe.Button1.Visible = true iframe.Button1.ItemName.Value = items[1].Name iframe.Button1.Text = items[1].Name iframe.Button2.Visible = true iframe.Button2.ItemName.Value = items[2].Name iframe.Button2.Text = items[2].Name iframe.Button3.Visible = true iframe.Button3.ItemName.Value = items[3].Name iframe.Button3.Text = items[3].Name iframe.Button4.Visible = true iframe.Button4.ItemName.Value = items[4].Name iframe.Button4.Text = items[4].Name end end end plr.Backpack.ChildAdded:connect(updateinven) plr.Character.ChildAdded:connect(updateinven)
Time to use a table loop! This should make it shorter:
local plr = game.Players.LocalPlayer local buttons = script.Parent.IFrame:GetChildren() local items = plr.Backpack:GetChildren() local iframe = script.Parent.IFrame local buttons = {iframe.Button1, iframe.Button2, iframe.Button3, iframe.Button4} function updateinven() for i = 1,#items do buttons[i].Visible = true buttons[i].ItemName.Value = items[i].Name buttons[i].Text = items[i].Name end end plr.Backpack.ChildAdded:connect(updateinven) plr.Character.ChildAdded:connect(updateinven)