Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to change the color of all parts in workspace if they have a certain material?

Ground = game.Workspace:GetChildren()
wait(0.5)
if Ground.Material == ("Grass") then
	Ground.BrickColor = BrickColor.new("Institutional white")
	Ground.Material = Enum.Material.Sand
end

I tried to make it work. No errors but nothing happens?

3 answers

✓ Accepted answer

You have to do something first before you even consider changing BrickColor and Material.

I highly suggest that you check to see if the child is a BasePart using Instance:IsA(). This is because if the for loop encounters a userdata that isn't a descendant of the BasePart class (which means that the child isn't either a Part, MeshPart or UnionOperation), it will error out because BrickColor and Material will not be valid properties of that child. This can easily happen if you have a few models assorted throughout the workspace. Models are not descendants of the BasePart class, and therefore they do not have the BrickColor or Material properties.

For assigning the Material property to a value, strings have been deprecated. Enums are now heavily favored for changing the Material of a BasePart. A full list of material Enums can be found here.

Here is an example of what I just explained to you:

for _, inst in pairs(workspace:GetChildren()) do
	if inst:IsA("BasePart") then
		if inst.Material == Enum.Material.Grass then
			inst.BrickColor = BrickColor.new("Institutional white")
			inst.Material = Enum.Material.Sand
		end
	end
end

1 comment

0

Also comparing them to strings may not work as material is of type ENUM not of type STRING. roblox might accept strings when writing to the property, but reading it for comparison may not work. Nice answer

Something you're doing wrong:

if Ground.Material == ("Grass") then

What you're doing wrong here is using a string instead of an Enum property.

if Ground.Material == Enum.Material.Grass then

Also, it should be a lot better just to use a loop.

for i, v in pairs(Ground) do

Here's the improved script:

Ground = game.Workspace:GetDescendants()
wait(0.5)
for i, v in pairs(Ground) do
	if v:IsA("BasePart") then
		if v.Material == Enum.Material.Grass then
			v.Material = Enum.Material.Sand
			v.BrickColor = BrickColor.new("Institutional white")
		end
	end
end

I hope this helped!

local children = game.Workspace:GetChildren()

for i = 1, #children, 1 do
if children[i].Material == "Grass" then
children[i].Material = "Sand"

end
end

3 comments

0

Thanks!

0

Not a good answer. Assigning the Material property to a string has been deprecated. Use the Enums for Material.

0

-1 for no explanation

This discussion is preserved as it was. New answers, comments, and votes are closed.