I am trying to create a Custom Backpack UI for my game, However there is an issue with the script.
When a Tool is removed, Everything is the Toolbar gets cloned, And I’m not sure how to fix it. The Images and Script are listed below
Script:
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local Backpack = LocalPlayer:WaitForChild("Backpack")
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")
local Main = script.Parent.Main
local Toolbar = Main.Toolbar
local Inventory = Main.Inventory
game:GetService("StarterGui"):SetCoreGuiEnabled(Enum.CoreGuiType.Backpack, false)
local Keybinds = {
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Zero"
}
local function CheckInput(Input, IsTyping)
local KeyCode = tostring(Input.KeyCode):split(".")[3]
local Callback = Keybinds[tonumber(KeyCode)]
if not IsTyping and Callback then
Callback()
end
end
local function CreateToolItem(Tool)
local ToolItem = Inventory.ToolItem:Clone()
ToolItem.LayoutOrder = #Toolbar:GetChildren() + 1
ToolItem.Name = Tool.Name
ToolItem.ItemName.Text = Tool.Name
ToolItem.Num.Text = tostring(ToolItem.LayoutOrder)
ToolItem.Parent = Toolbar
end
local function RemoveToolItem(ToolName)
local ToolItem = Toolbar:FindFirstChild(ToolName)
if ToolItem then
ToolItem:Destroy()
end
end
for _, Tool in pairs(Backpack:GetChildren()) do
if Tool:IsA("Tool") then
CreateToolItem(Tool)
end
end
Backpack.ChildAdded:Connect(function(Tool)
if Tool:IsA("Tool") then
CreateToolItem(Tool)
end
end)
Backpack.ChildRemoved:Connect(function(Tool)
if Tool:IsA("Tool") then
RemoveToolItem(Tool.Name)
end
end)
game:GetService("UserInputService").InputBegan:Connect(CheckInput)