How to get all descendants from a Parent of the same class?

Hi Developers! :wave:
I’m struggling to make a feature in my game which can change the colour of only buttons and frames, but I don’t know how.

The problem is that I have no idea how to get all children from the hierarchy I have in my StarterGui…

If you need some more detailed info, tell me please! Any help is appreciated! :hidere:

local function GetDestandensByClass(obj: Instance, className: string)
	local destandens = {}
	for _, destand in obj:GetDescendants() do
		if not destand:IsA(className) then continue end
		table.insert(destandens, destand)
	end
	return destandens
end

-- Example
local screenGui = Instance.new("ScreenGui")
local frame = Instance.new("Frame")
local button = Instance.new("TextButton")

screenGui.Parent = game.Players.LocalPlayer.PlayerGui
frame.Parent = screenGui
button.Parent = frame

print(GetDestandensByClass(screenGui, "TextButton")) -- { button }
1 Like

@Srat_hochu228 effectively wrote the whole thing for you, but I’ll clear up what it’s doing.

First, let’s consider how to get all the children in the first place. To do that, you can use something like ScreenGui:GetDescendants(). This will give you all the descendants of an object (in this case, the screen GUI) in a giant table.

Then, you can run a loop on this table. Roblox has a function called :IsA() which you can call on any instance. inside the parentheses is the string ("Frame" or "TextButton"). It will return true or false dependent on if it is that class or not.

If true, you can add the instance into a new table, and then once the loop has completed that new table will have all the instances with the class that you want.

3 Likes

Thank you a lot @Aawesome10001 for more detailed information, I knew this :GetDescendants() thing, but I didn’t know it could do deep search! And big thanks to @Srat_hochu228 , you really helped me to see an actual and practical example! (имбовый ник у тебя))

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.