Randomize the color and material of parts that are in a folder

Hey again! Today, I have a script that when the game starts, it randomizes the color and material of parts that are in a folder! Take a look. Note: I have other versions of the script that DO work, I just wanna sort out how to use one script to randomize a couple of parts.

local shelvedProducts = game.Workspace.ShelvedProducts:GetChildren()

local Materials = Enum.Material:GetEnumItems() 
local RandomMaterial = Materials[math.random(#Materials)] 

for _, product in pairs(game.Workspace.ShelvedProducts:GetChildren()) do
	shelvedProducts.Material = RandomMaterial
	shelvedProducts.Color = Color3.fromHSV(math.random(0,255)/255, 1, 1)
end

When I run the game, I get no error but the parts do not randomize. Any idea what could be the problem here?

Change shelvedProducts is a table change, it into the ‘product’ variable so it should be:

product.Material = RandomMaterial
product.Color = Color3.fromHSV(math.random(0,255)/255, 1, 1)

It didn’t work.

But here is the new code:

local products = game.Workspace.Products:GetChildren()

local Materials = Enum.Material:GetEnumItems() 
local RandomMaterial = Materials[math.random(#Materials)] 

for _, product in pairs(game.Workspace.Products:GetChildren()) do
	products.Material = RandomMaterial
	products.Color = Color3.fromHSV(math.random(0,255)/255, 1, 1)
end

Try printing and tell me the output.
print(#game.Workspace.Products:GetChildren())

It printed the number 4 (3 parts and the script).

Ok, I will try it. Could you explain the script so I know why it didn’t work?

shelvedProducts.Material just writes to the table of the children, change “shelvedProducts” inside the loop to “product”.

1 Like

Scripts don’t have a color property you’re trying to change the color of the script but scripts don’t have a color property we first check if it is a part before we change it’s color. Since the script itself is located in the folder it will also loop through the script.

local products = game.Workspace.Products:GetChildren()

local Materials = Enum.Material:GetEnumItems() 
local RandomMaterial = Materials[math.random(#Materials)] 

for _, product in pairs(products) do
     if product:IsA("BasePart") then
	     product.Material = RandomMaterial
	     product.Color = Color3.fromHSV(math.random(0,255)/255, 1, 1)
     end
end

Here try this, hopefully is this your solution.

It sure is! Thanks you so much for the help!