How to remove duplicate same tool in backpack roblox studio

Help how to make sure that there can not be more than one specified tool in the backpack, for example: the NPС gives me one tool and I want to get another, but when you get this tool, the last one is deleted and only one will remain, sorry for wording this sentence so badly

Would have to use WaitForChild:() or something along the lines like that to check if the tool name is there and if not then give the item, or just simply make the npc not give the item the second time.

it is best to avoid putting duplicate items in the backpack in the first place, but this script should work for you:

local script, inside StarterPlayerScripts

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer

local indexedItems = {}
local function removeDoubles(addedItem)
    for _, item in pairs(localPlayer.Backpack:GetChildren()) do
        if not table.find(indexedItems, addedItem.Name) then
          table.insert(indexedItems, addedItem.Name)
        else
          addedItem:Destroy()
        end
    end
end

localPlayer.Backpack.ChildAdded:Connect(removeDoubles)

Sorry, it didn’t work, error

21:25:58.931 Backpack is not a valid member of Player "Players.KEFFIRYT" - Client - LocalScript:15
21:25:58.931  Script 'Players.KEFFIRYT.PlayerScripts.LocalScript', Line 15   
21:25:57.175  ServerScriptService.Script:15: attempt to index nil with 'Backpack'  -  Server - Script:15 21:25:57.175  Script 'ServerScriptService.Script', Line 15  -  Studio - Script:15"

I’m pretty sure backpack loaded in after the local script does, oversight by me.

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local backpack = localPlayer:WaitForChild("Backpack")

local indexedItems = {}
local function removeDoubles(addedItem)
    for _, item in pairs(backpack :GetChildren()) do
        if not table.find(indexedItems, addedItem.Name) then
          table.insert(indexedItems, addedItem.Name)
        else
          addedItem:Destroy()
        end
    end
end

backpack.ChildAdded:Connect(removeDoubles)

idk why it dont work

What does the code for giving the tool look like?

Heres a script that gives you a tool without it being duplicated.

--Script in ServerScriptService
--Part with click detector

local ToolGiver = workspace.ToolGiver
local ClickDetector = ToolGiver.ClickDetector
local Tool = game.ReplicatedStorage.Tool

ClickDetector.MouseClick:Connect(function(player)
	if player.Backpack:FindFirstChild("Tool") then return end
	local Tool = Tool:Clone()
	Tool.Parent = player.Backpack
end)

5 Likes