Once the car explodes its suppose to make all the white parts turn into “CorrodedMetal”,
but it only makes some parts change material but not all.
local CarBody = script.Parent.Parent:GetChildren()
for _, v in ipairs(CarBody) do
if v:IsA("Part") and v:IsA("UnionOperation") then
v.Material = "CorrodedMetal"
end
end
First, the GetChildren method of an object returns an array of all the object’s direct children, but not its grandchildren or deeper descendants. This means that if the parts you want to change the material of are not direct children of script.Parent.Parent , they will not be included in the CarBody array.
To get all the descendant parts of script.Parent.Parent , you can use a recursive function that iterates through all the children of the object, and then all the children of those children, and so on. Here is an example of how you could modify your code to do this:
local function getDescendantParts(object)
local parts = {}
for _, child in ipairs(object:GetChildren()) do
if child:IsA("Part") then
table.insert(parts, child)
end
for _, descendantPart in ipairs(getDescendantParts(child)) do
table.insert(parts, descendantPart)
end
end
return parts
end
local CarBody = getDescendantParts(script.Parent.Parent)
for _, v in ipairs(CarBody) do
v.Material = "CorrodedMetal"
end
The second issue with your code is that it only changes the material of parts that are both a Part and a UnionOperation . It is not possible for a single object to be both of these types, so this condition will always evaluate to false. To change the material of all the parts in the CarBody array, you can simply remove this condition.