How do I get a certain type of child?

I’m using a for loop to get all the children. Currently, I’m using GetDescendants for this because FindFirstChild doesn’t work. I also have a second problem I need it to get only parts.

Here is the code:

for i,v in pairs(script.Parent:GetDescendants()) do
	print(i,v)
end

FindFirstDescendant() can help, but cant be used in “for i,v” loop
To get parts only, use: FindFirstChildWhichIsA() or FindFirstAncestorWhichIsA()

1 Like
function GetDescendantsOfClass(Parent, Type)
    local Table = {}

    for _, Object in ipairs(Parent:GetDescendants()) do
        if Object:IsA(Type) then
            table.insert(Table, Object)
        end
    end

    return Table
end

you can use the function to get all descendants of class
you would need to call it like this

GetDescendantsOfClass(script.Parent, "BasePart")

the first argument is the parent and the second argument is the class type

3 Likes

this only works if the name is called part I need it to find out what type of object it is.

Use FindFirstChildOfClass or FindFirstChildWhichIsA which gets the type/className of the instance. And can you explain a bit more about the “type”?

no it works for every instance that is a BasePart

did you even test it?

I did and it did’nt print anything so I assumed that it only prints something if the object is named “BasePart”.

if you don’t find anything it should at least print a table

are you sure you printed it with print()?

print(GetDescendantsOfClass(script.Parent, "BasePart"))

You can use FindFirstChildWhichIsA(instance type here). This returns the first occurrence of the type of instance:
https://developer.roblox.com/en-us/api-reference/function/Instance/FindFirstChildWhichIsA


If you want to get all of the instances with that type you can loop through the descendants and store the correct ones in a table:

local Objects = {}
for _, Object in ipairs(Somthing:GetChildren) do
    if Object:IsA("Part") then -- If the object is a part ten this will pass
        table.insert(Objects, Object)
    end
end

yes I am sure and it didn’t print anything
I think I’m just going to use a table because I don’t see any other solution.

I literally got back from school and tested it
I put this code inside serverscriptservice

server script
function GetDescendantsOfClass(Parent, Type)
	local Table = {}

	for _, Object in ipairs(Parent:GetDescendants()) do
		if Object:IsA(Type) then
			table.insert(Table, Object)
		end
	end

	return Table
end

print(GetDescendantsOfClass(workspace, "BasePart"))
output
{
    Baseplate,
    Terrain,
    SpawnLocation
}

this proves you weren’t doing it right

1 Like
for i, v in pairs(script.Parent:GetDescendants()) do
	if v:IsA("Part") then
		--do stuff here
	end
end
for _, descendant in ipairs(script.Parent:GetDescendants()) do
	if descendant:IsA("Part") then
		print(_, descendant)
	end
end