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

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

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

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

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