Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do you count the amount of a specific item in a folder or workspace?

my script doesn't work and idk why but I'm trying to figure out how to count the amount of a item in workspace excluding other items so

for i,v in pairs(#game.Workspace:GetChildren()) do
   if v.Name == "Bubble" then
       game.Players.LocalPlayer.PlayerGui.Bubbles.Amount.Text = v
    end
end

trying to make it only count "Bubble" but it doesn't work

3 comments

0

Remove the # before game

0

but that doesnt really count the amount of bubbles would be in the workspace

0

Or put them all into a folder then just do #workspace.Bubbles:GetChildren()

1 answer

Pretty simple to do

local bubblecount = 0 -- Define variable for counting
for i,v in pairs(game.Workspace:GetChildren()) do -- Get all of the children
   if v.Name == "Bubble" then -- Detect if the children are named bubble
	bubblecount = bubblecount + 1 -- If the child is named bubble, add one to the count
    end
end
 game.Players.LocalPlayer.PlayerGui.Bubbles.Amount.Text = bubblecount -- Once the for loop ends, set the bubble amount text to the count we got from the loop.

Basically everytime you run your for loop, and a bubble is detected a virtual number will go up by 1 which will be used to set your gui text.

Now lets analyze your code and see why it didnt work.

for i,v in pairs(#game.Workspace:GetChildren()) do -- Gets the children - Halfway correct step. Using #game.Workspace:GetChildren()) would actually just run the for loop for however many children there are, but without the #, it would actually iterate through the parts.
   if v.Name == "Bubble" then -- Determine if child is a bubble - Correct step
       game.Players.LocalPlayer.PlayerGui.Bubbles.Amount.Text = v -- Set the gui's text to v - Incorrect step. V is the child, it has no way of determining how many there was. Using i would be the correct step, however since you have parts not named bubble, your count would be wrong.
    end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.