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

Grabbing all Children of a model and adding functions

How do I grab all the children from a model (Parts with different names) and make them for example the color red or transparent?

3 answers

✓ Accepted answer

ROBLOX has a handy method named GetChildren that, when used on an object, will return all of the object's children. This is really useful for affecting all children of an object. For example...

workspaceChildren = workspace:GetChildren()

... will return a table full of the children of Workspace.

To edit each child, we will have to iterate through each child and edit them one by one. In programming, this would require a loop. Some loops that Lua provides for you to use are while, for, and repeat. In this case, it would probably be more useful to use a for statement, for simplicity and clarity.

Here's an example, assuming the variable model is equal to the target model you had in your question.

for name, child in pairs(model:GetChildren()) do -- Looping through all of the children
	if child:IsA("BasePart") then -- Checking if it's a part
		child.BrickColor = BrickColor.Red() -- Setting it to red
		child.Transparency = 0.2 -- Transparency
	end
end)

What if your model had models within models or parts within parts? A simple for loop wouldn't be able to paint all the parts within the model red. In order to do this, we'll need to use a recursive function, also known as recursion. I was going to write you some code but it appears that the recursion page on the wiki gives an example related to your question.

function colorAllThePartsIn(parent)
	for _, child in ipairs(parent:GetChildren()) do
		if child:IsA("BasePart") then
			child.BrickColor = BrickColor.new("Bright red")
			child.Transparency = 0.5 -- my modification
		elseif child:IsA("Model") then
			colorAllThePartsIn(child) -- recursive step
		end
	end
end
 
colorAllThePartsIn(workspace.Model)

Sources:

• http://wiki.roblox.com/index.php?title=Recursion

Use the pairs() iterator along with a for loop.

for i,v in pairs( Workspace.ModelName:GetChildren() ) do
	if v:IsA("BasePart") then -- make sure it is a physical part
		v.Transparency = .5
		v.BrickColor = BrickColor.Red()
	end
end

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