Search every single Child (And the Children of that Child)

so, I wanted to know if there is a better way of searching children of workspace as well as the children of the child completely.

So like, Let’s say there’s a model with even more models inside of it and I want to search every child of that model, rather than doing :GetChildren() or :GetDescendants Continuously, I want a better way of doing it.

2 Likes

The only way is using GetDescendants() and it’ll return all of the childrens of the mode, and the children Of the children etc.

1 Like

That’s where recursion comes in handy:

function GetChildrenRecursive(ThingThatHasChildren)
	for Index, Value in pairs(ThingThatHasChildren:GetChildren()) do
		print(Value)
		if #Value:GetChildren() > 0 then
			GetChildrenRecursive(Value)
		end
	end
end

GetChildrenRecursive(workspace)

I haven’t tested this code that much, so lemme know if this works.

1 Like

There is another method actually. FindFirstChild has a second parameter for recursive searches.

workspace:FindFirstChild("something", true)
4 Likes

Multiple Methods (already as been said by others):

-- Method 1: Recusive Argument
-- Credit to (@JarodOfOribiter) (sorry that I copied lol)

local Instance = workspace:FindFirstChild("something", true) -- Recursive Search using FindFirstChild
if Instance then -- if Instance Exists
    EX(Instance) -- Fires for Instance
end 

-- Method 2: Recursive functions

-- Credit to (@ABrainDilemma)

function EX(obj) -- Normal function
    -- perform something on the Object
end

function Recursive_EX(obj) -- Recursive
    EX(obj) -- Fires Normal
    
    for _,instance in obj:GetChildren() do -- Iterates through objects children
         Recursive_EX(instance) -- fires Recursive function for Child within Instance
    end
end

-- Method 3: GetDescendants

-- Credit to (@DeDe_4242)

for _,instance in obj:GetDescendants() do -- Iterates through descendants
     EX(instance) -- Fires function or all Children
end

However I’m not entirely sure whats faster or whats not.

1 Like

Alright, thanks for the help (though, it was kinda a dumb question)

would that work for something like this?

image

Yes.

My idea would be to make a function, and then to get the children, and run the function again to make a loop(?)

But… :GetDescendants literally says it’ll get you everything so there’s no need to use it continuously. The best way to do it is :GetDescendants

2 Likes

Using ClearAllChildren() should work i believe

sorry to bump this