GetChildren Help

Hello,

I have this script below (it works obviously): This detects TextButton’s under a frame. Now, say I wanted to find the TextButton even ‘deeper’ for the lack of a better term in the frame like this:
Screen Shot 2021-12-01 at 4.30.49 PM

Instead of this:
Screen Shot 2021-12-01 at 4.31.47 PM

How should I change the (script.Parent:GetChildren()) to find the TextButton under another frame?

for _,Button in ipairs(script.Parent:GetChildren()) do
	if Button:IsA("TextButton") then
		Button.Activated:Connect(function()
			game.ReplicatedStorage.ChangeTeamEvent:FireServer(Button.Name)
		end)
	end
end

You could use :GetDescendants() and check if it is a TextButton using :isA()

Example code:

for _, x in pairs(GUI:GetDescendants()) do
 if x:isA("TextButton") then
  -- Code
 end
end
2 Likes

Instance:GetDescendants() gets every part below the instance.

Like the other people are saying, you can use Instance:GetDescendants. However, there is another option. You could also use recursion.

local function Recursion(instance)
	for _,child in pairs(instance:GetChildren()) do
		if child:IsA("TextButton") then
			-- do stuff
		else
			Recursion(child)
		end
	end
end

In all honestly you should still use :GetDescendants, unless you only want to iterate to a certain depth. In that case you could do something like this:

local function Recursion(instance, depth)
	for _,child in pairs(instance:GetChildren()) do
		if child:IsA("TextButton") then
			-- do stuff
		elseif math.abs(depth) > 0 then
			Recursion(child, depth-1)
		end
	end
end

This will only iterate a certain amount of descendants.

2 Likes

Snipping this post, nothing to see.

local frame = script.parent
local rs = game:GetService("ReplicatedStorage")
local changeTeam = rs:WaitForChild("ChangeTeamEvent")

for _, Button in ipairs(frame:GetDescendants()) do
	if Button:IsA("TextButton") then
		Button.Activated:Connect(function()
			changeTeam:FireServer(Button.Name)
		end)
	end
end

I’d declare a variable reference to the RemoteEvent instance at the top of the script like this.

I think you are confusing :GetChildren with :FindFirstChild. As far as I know, :GetChildren doesn’t have a recursive parameter while Instance | Roblox Creator Documentation does. Plus, if it did, wouldn’t that make :GetDescendants useless API bloat?

Also, the point of my post was to show an example of how recursion might be done and how it could be modified to give greater control.

You are correct, for some reason I was responding in regards to one while thinking of the other.