How To Get Children Of Parts?

So, I was wondering how I can get the children of parts or objects. An example is below.

Workspace

Camera

Terrain

Baseplate
Part
Part
Part
Part

I was wondering, how can I get all children from the baseplate then all children of the parts?

I tried GetDescendants but I don’t think it worked. Also, GetChildren only would get the Baseplate.

1 Like

If you do

for i,v in ipairs(workspace:FindFirstChild("Baseplate"):GetChildren()) do
  print(i,v)
end

It will go through all the children and print out the tostring() of their name.
The variable v is then the child object it got.

To print all the children of the parts below as well

function getChildren(parent)
  local children = parent:GetChildren()
  for i,v in pairs(children) do
    print(i,v)
    getChildren(v)
  end
end

getChildren(workspace:FindFirstChild("Baseplate"))

On the other hand, and easy way to get all the children if you don’t need to do things to each one individually before moving to the next, is using GetDescendants()

for i,v in ipairs(workspace:FindFirstChild("Baseplate"):GetDescendants()) do
  print(i,v)
end
4 Likes

If you want to perform an action with those parts you can use the for loop


For i,v in Ipairs(game.Workspace.Baseplate:GetChildren()) do
——function in here
end

2 Likes

Probably because you did workspace:GetChildren().

GetChildren() only gets the children of the said part. GetDescendants() however will get every part within the part (parts parts and so forth).
Bit confusing I know lol.

To get the baseplates children simply do a loop like the above posts suggested but with

workspace.Baseplate:GetChildren()
1 Like

You shouldn’t be using foreach/foreachi, those are deprecated methods of iterating over tables. Should maintain consistency and modern practices in your code by using a for loop with the appropriate generator applied. Specifically, because you’re working with arrays, ipairs, not pairs.

1 Like

Don’t reference game.Workspace, it’s slower. Also, the incorrect capitalisations in your code are bothering me because Lua is case sensitive.

@Aiden_12114 I personally suggest using workspace:GetDescendants() and then filtering down to what you want.

I was just using it as a quick way here to demonstrate how to print it, because I was too lazy to type it out. Then I typed it out… I also had the code for the for loop after it. (Gonna remove the .foreach and just have the for loop below it.)