Can I use :GetChildren() but only have it get children that are, for instance, tools?
Can I GetChildren of only a certain class?
4 answers
Yes, you can. By using :IsA() you can easily identify what you want from a group of items. For example let's say you had a model with random items:
local Model = script.Parent
for _, item in pairs(Modle:GetChildren()) do
if item:IsA('Tool') then
-- do something to the tool
end
end
Hopefully, this helped. Best of luck developer. Comment if you have problems.
Unfortunately, while this has been requested on the official developer forum, it is not [yet] a feature. You can, however, use a loop containing an if statement to check if an item is a specific class.
local newTable = {}
local items = something:GetChildren()
for i,v in pairs(items) do
if v:IsA("Tool") then -- Any class can go here. You can also put multiple statements.
table.insert(newTable,v)
end
end
-- do something with newTable here.
Use :IsA(className) to check the class of an instance.
function GetChildrenOfType(parent, t)
children = {}
for i, v in pairs(parent:GetChildren()) do
if (v:IsA(t)) then
table.insert(children, v)
end
end
return children
end
At the moment we are not able to only GetChildren of one class. This can be achieved in a few ways but the best way would be using a generic for loop to add all children of that class to a table.
childrenOfClass = {} -- Table that the children will be put in.
for _, v in ipairs(parent:GetChildren()) do -- Loops through ALL children
if v:IsA("Class") then -- Checks if child is of a specific class.
table.insert(childrenOfClass, v) -- Adds child to table
end
end
You could make this more useful by turning it into a function like this:
function GetChildrenOfClass(parent, class)
children = {} -- Table of children
for _,v in ipairs(parent:GetChildren()) do -- Loops through ALL children
if v:IsA(class) then -- Checks if "v" is of class "class"
table.insert(children, v) -- Adds "v" to table
end
end
return children -- Sends the children back to the line that called it.
end
If my answer solved your problem, please remember to mark it as correct!
3 comments
Your definition of IsA is wrong.
Your definition of IsA is wrong.
No it is not.
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
Not the best way. Using :IsA() returns classes that INHERIT from that class. Not the actual class. So if item.ClassName == "Tool" then. His question also said of CERTAIN CLASS.
You raise an interesting point, but are there any concrete classes which themselves inherit from other, concrete classes? Also, is there ever a situation where it is correct to catch instances of a class, but not of a sub-class? Based on OO-principles I'd argue no.