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

How do you get All of the Descendants of an Instance?

I'm trying to find all of the ClassName SelectionBox in the workspace so I can change their color. However, they all have different Parents and Children so it would be laborious to make a script ....:GetChildren() for all of them.

How can I get All of the Descendants of a said instance such as Workspace?

1 comment

0

Wow thanks for this. I don't understand what the ; do though.

2 answers

✓ Accepted answer

Don't use recursive functions - Iterative ones are better

function GetDescendants(i)
    local queue = {};
    local returns = {};
    local v = i;
    while v do
        local t = v:GetChildren();
        for i = 1, #t do
            local v = t[i]
            returns[#returns+1] = v;
            queue[#queue+1] = v;
        end;
        v = queue[#queue];
        queue[#queue] = nil;
    end;
    return returns;
end;

What you need to do

So, you're trying to gather all of the SelectionBoxes in workspace and change their color?

For this, you can use recursion. Recursion is essentially re-iterating a function upon itself. Like if you were to go;

function a()
	a()
end

This is recursion. But be wary when using recursion, as you can easily end up with a stack overflow. Stack overflow errors happen when you call a function inside itself too many times within a short amount of time, with no yeild. The code above would give you a stack overflow error.

So, to use recursion to your advantage? You need to make a function that iterates through workspace. This can be done through a generic for loop. Check if the current child is a SelectionBox, and if it is recolor it. Then, you can recall the function on itself with each child.



Code

--'model' being the group to search
--'color' being the color to change the selectionboxes to
function search(model,color)
	local function recurse(m,c)
		--Iterate through the model
		for _,v in next, m:GetChildren() do
			--Check if the object matches
			if v:IsA("SelectionBox") then
				--If so, change the color
				v.Color3 = color
			end
			if #v:GetChildren() > 0 then
				--If there are objects left, recurse.
				recurse(v,t)
			end
		end
	end
	recurse(model,color)
end

Now you can call the function with the specified arguments.

search(workspace,Color3.new(1,0,0))
--Red

2 comments

0

NO BAD NO RECURSION BAD GOUL

0

RECURSION IS YUM THO AND WORKZZ

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