How do I grab all the children from a model (Parts with different names) and make them for example the color red or transparent?
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...
1 | 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.
1 | for 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 |
6 | 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.
01 | function 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 |
10 | end |
11 |
12 | colorAllThePartsIn(workspace.Model) |
Sources:
Use the pairs() iterator along with a for loop.
1 | for 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 |
6 | end |
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?