Issues with math.random using # of parts in an array

I would like to take a random part out of the array and make it Bright green. The issue is that my code sometimes makes 3 parts Bright green, sometimes 2, and sometimes none. I’ve tested to see if print(#math.random(randomizer:GetChildren()) prints the correct number, and it does. So, if it’s checking to see if a number is between 1-24 and the index value matches that random value, why would it be making multiple parts bright green?

workSpace = game:GetService("Workspace")
randomizer = workSpace.Randomizer

for i, v in pairs(randomizer:GetChildren()) do
	if i == math.random(1,#randomizer:GetChildren())then
		v.BrickColor = BrickColor.new("Bright green")
	end
end

image

Your current code will generate a random number for each part that it loops through, therefore it could never choose a part. Try this instead:

workSpace = game:GetService("Workspace")
randomizer = workSpace.Randomizer

local randomPart = math.random(1, #randomizer:GetChildren())
for i, v in pairs(randomizer:GetChildren()) do
	if i == randomPart then
		v.BrickColor = BrickColor.new("Bright green")
	end
end
1 Like

Ah, yeah that makes sense. I forgot that it would loop through each part. Thanks.

1 Like

A better way to go about this is to simply not use a for loop!

local children = randomizer:GetChildren()
local part = children[math.random(1, #children)]
part.BrickColor = BrickColor.new("Bright green")

There is absolutely no need to be looping through an entire table for this application

1 Like

Actually, that would error because part would be a number.

2 Likes

My bad, I’ve corrected my code.