How would I check for duplicated tools after adding them?

Hi all,
Currently, I’ve been trying to design my own inventory system, but have come into an issue - Stacking. My solution had been to delete any extra tools that appear in the inventory and add it to a value. Only that it’s not destroying extra tools - it’s destroying all of them.

Current script is:

if adding:GetAttribute("Stackable") == true then
	for i,v in pairs(player.Backpack:GetChildren()) do
		if v.Name == adding.Name then
			print(adding.Name)
			debris:AddItem(adding,0)
			break
		end
	end
end

The issue is this script is that, since this runs at the same time as an item is added to the player’s inventory - it will delete all the items that were added. (By that, I mean the item is added to the player backpack, GetChildren gets those items that were just added, and this script destroys all of those items in return. For example, 3 apples is added at the same time - the code detects that there’s multiple apples, but destroys all of them, and doesn’t leave one) Does anyone have a workaround?

2 Likes

if v.Name == adding.Name and v ~= adding then

2 Likes

Generally comparing the name is enough, see post above, but this can create a few issues if you have two tools named the same.

A more bulletproof method is to give each instance its own “unique” identifier through CollectionService tags, but again, if you know your tool names aren’t going to be duplicate, just use what Nyrion posted, comparing names

1 Like

The instance itself is an identifier, that’s the point of my post above. Basically v.Name == adding.Name is true for instances with the same name, but v == adding can only be true if those instances are the same instance(basically 2 clones compared that way give false).

This can be tested with the following code:

local p = workspace.Baseplate 
local c = p:Clone()
c.Parent = p.Parent 

print(p == c) --false
print(p.Name == c.Name) --true(basically all properties are equal)

c:Destroy()

But as you said yourself if you have 2 different tools(actual different tools within the game context, not identical duplicate tools) but they happen to have the same name, then you have to figure out either a different way to compare them or add your own identifiers.

for i, v in pairs(player.Backpack:GetChildren()) do
if v.Name == "toolname" and i > 1 then
local toolamount = i
repeat
v:Destroy()
toolamount = toolamount - 1
until toolamount == 1
end
end

if u see the edit it was bcuz i accidently sent it. hope this gives u an idea. not tested and ye.

1 Like

Can’t believe I didn’t manage to think about that, thanks to everyone that tried to help!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.