Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Grabbing all Children of a model and adding functions [closed]

Asked by
RSoMKC 45
11 years ago

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

Locked by JesseSong

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

Why was this question closed?

3 answers

Log in to vote
3
Answered by
Unclear 1776 Moderation Voter
11 years ago

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...

1workspaceChildren = 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.

1for name, child in pairs(model:GetChildren()) do -- Looping through all of the children
2    if child:IsA("BasePart") then -- Checking if it's a part
3        child.BrickColor = BrickColor.Red() -- Setting it to red
4        child.Transparency = 0.2 -- Transparency
5    end
6end)
Ad
Log in to vote
5
Answered by
nate890 495 Moderation Voter
11 years ago

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.

01function colorAllThePartsIn(parent)
02    for _, child in ipairs(parent:GetChildren()) do
03        if child:IsA("BasePart") then
04            child.BrickColor = BrickColor.new("Bright red")
05            child.Transparency = 0.5 -- my modification
06        elseif child:IsA("Model") then
07            colorAllThePartsIn(child) -- recursive step
08        end
09    end
10end
11 
12colorAllThePartsIn(workspace.Model)

Sources:

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

Log in to vote
0
Answered by
MrNicNac 855 Moderation Voter
11 years ago

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

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