How do I find how many instances there are of a instances' child?

Basically, I am making an inventory system and I need to figure out how many of the same tools are in the player’s backpack.

local SameTools = 0

--Do the code below whenever you need to check for the tools:

local ToolCheckName = "Tool" -- change to the name of the tool that you are looking for
for I,v in pairs(game.Players.LocalPlayer.Backpack:GetChildren()) do
 if v.Name == ToolCheckName then
  SameTools += 1 
 end
end

print(SameTools) -- this variable now holds how many of the same tools the player has
local function getToolTotals(player)
	local tools = {}
	local backpack = player.Backpack
	for _, tool in ipairs(backpack:GetChildren()) do
		if tools[tool.Name] then
			tools[tool.Name] += 1
		else
			tools[tool.Name] = 1
		end
	end
	return tools
end

local tools = getToolTotals(player) --assume you have player instance to pass
for toolName, toolQuantity in pairs(tools) do
	print(toolName, toolQuantity)
end
2 Likes