Issue with GetChildren() not working properly?

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

Video below to show you the issue

1 Like

GetChildren() only looks one level down. What does the hierarchy of the car look like in Explorer?

Does that work for setting material? I thought you could only set it like this:
v.Material = Enum.Material.CorrodedMetal

You just had a small typo: v:IsA("Part") and v:IsA("UnionOperation") should be v:IsA("Part") or v:IsA("UnionOperation")

(An instance can’t be a part and a union. You could simplify the code to v:IsA("BasePart") to include unions, parts, and mesh parts.)

3 Likes
v.Material = "CorrodedMetal"

still works for setting Materials

1 Like

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.

1 Like

Alright thank you

1 Like

You’re welcome my friendily friend :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.