Firing an event when new child enters backpack also fires when player unequips (How to prevent)

Sorry if I worded the title badly.

I wanted to make it so that when a player is given a gear, it will fire an event, I did this with Backpack.ChildAdded()
However, this method makes it so that when the player unequips any gear, it will fire the event as it goes from the character back to the backpack.

Here is my code:

local plr = game.Players.LocalPlayer
local backpack = plr.Backpack

backpack.ChildAdded:Connect(function(tool)
    print("hi")
)

code is in StarterGui by the way

Again, it will print ‘hi’ every time the player gets a new tool, but unfortunately it also includes when they unequip any tool. Anyway to the prevent this? I’ve tried looking for solutions on the dev hub on the humanoid and tool events but I didn’t find the solution & on the devforum.

Also sorry if I missed an easy solutions, thanks

1 Like

Could you check if tool.Parent == nil?

2 Likes

You should use Tool.Equipped or Tool.Unequipped at all.

1 Like

You are using ChildAdded, which registers everything that is added. Naturally, when you equip a tool, it gets removed from the backpack, and when unequip, it gets added back to the backpack. It’s not a practical method at all.

If you really want to use StarterGui, then you should create a table for the tools.

local Tools = {} -- your tools
local plr = game.Players.LocalPlayer

And then search which tool was added from the list.

2 Likes

One hacky way to do it would be to have a function listening to when player unequips a tool with .ChildRemoved, and have a variable that stores last unequipped tool, then when a tool is added to the backpack you could check if its same as the unequipped one:

local player = game.Players.LocalPlayer

local unequipped = nil

player.Character.ChildRemoved:Connect(function(child)
	if not child:IsA("Tool") then return end
	unequipped = child
end)

player.Backpack.ChildAdded:Connect(function(child)
	if child == unequipped then return end
	print("added")
end)

Other ways could include keeping track of items in the backpack or having an attribute, bool value or something inside a tool that will tell the script its just been added to the backpack and not unequipped.

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

local BackpackItems = {}

Backpack.ChildAdded:Connect(function(item)
    local hasItem = table.find(BackpackItems, item)
    if not hasItem then
        Event:FireServer(...)
        table.insert(BackpackItems, item)
    end
end)

it still fires when you unequip, that is where the tool is stored when it is not partened to your character

make a table called tool cache and use table.find on that table to check if this instance has already been added