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

How can I improve my in pairs loop? The parts should get a random color that is in a table

Hey, my script is supposed to change all the parts in a model to either black, bright red or bright yellow. The thing is that it changes all the parts to the same color. So when I test the game it change the parts to 1 color only. What can I do to make it random for every part? I tested "v.BrickColor = BrickColor.Random(colors[index])". That did not work well because it took all the colors in the color wheel or what you call it.

color = script.Parent.Parent
db = true


local colors = {
	"Black",
	"Bright red",
	"Bright yellow"
	
}

local index = math.random(1,#colors)

local colorTiles = color:GetChildren()

colorTiles[1].BrickColor = BrickColor.new(colors[index])


print(colorTiles)


for i,v in pairs(colorTiles) do
	v.BrickColor = BrickColor.new(colors[index])
end


Anyways, I hope someone know how to fix my problem, thanks :) ,Xsodar

2 comments

0

Dump the "index" variable inside the in pairs loop and you should be all good to go

0

It just gives me this error: Workspace.Color Tiles.ColorTiles.ColorTilesScript:23: invalid argument #1 to 'new' (Color3 expected, got table). But I will try to figure it out

1 answer

✓ Accepted answer
local colorTiles = color:GetChildren()

local colors = {
	"Black",
	"Bright red",
	"Bright yellow"
}

for _, v in pairs(colorTiles) do
	v.BrickColor = BrickColor.new(colors[math.random(1, #colors)])
end

During each iteration of the for loop, it will index the table by a random integer between 1 and the length of the table. Hope this works for you :)

1 comment

0

Thank you! it works!

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