We do have :FindFirstChildOfClass() but It will only choose one... If I'm wrong please tell me. I want to know if there is a way to find all children from one class.
That I'm aware of, there is no built-in function to do it. The best way to get all children by a class is writing a function for it yourself, which is fairly simple!
Loop through the instance's children, check their class, if it matches the one you are looking for, then add it to a table. In the end, return the table.
It's fairly simple to write
01 | local function getChildrenOfClass(instance, class) |
02 | -- table to hold the children |
03 | local children = { } |
04 |
05 | -- looping through the instance's children |
06 | for i,v in pairs (instance:GetChildren()) do |
07 |
08 | -- check if the child's class matches the one we're looking for |
09 | if (v.ClassName = = class)) then |
10 | -- we add it to the table |
11 | table.insert(children, v) |
12 | end |
13 | end |
14 |
15 | -- we return the table, so that it can be used when calling the function |
16 | return children |
17 | end |
Afterwards, you can call your function whenever needed, and access it!
To access it, you can do it in the same way that you would for FindFirstChildOfClass()
!
1 | -- This will allow you to use the children you've selected using the function |
2 | local childrenOfClass = getChildrenOfClass(model, "Part" ) |
3 |
4 | for i,v in pairs (childrenOfClass) do |
5 | print (v.Name) -- This would output the part's name, you can do anything else with it! |
6 | end |
1 | function GetChildrenOfClass(Instance, Class) |
2 | local ChildrenOfClass = { } |
3 | for _, Child in pairs (Instance:GetChildren()) do -- iterate through table returned by GetChildren |
4 | if Child.ClassName = = Class then -- Check if ClassName matches Class Argument |
5 | table.insert(ChildrenOfClass, Child) -- insert into table |
6 | end |
7 | end |
8 | return ChildrenOfClass -- Return the table |
9 | end |