Randomize colors without repeats

I’m trying to make an object that changes colors randomly from a table of colors. However, despite the table modifications in the below code, there are still occasionally duplicate colors that occur in succession.

	local colors = {
		Color3.fromRGB(170, 64, 116),
		Color3.fromRGB(145, 86, 170),
		Color3.fromRGB(84, 95, 170),
	}
	local colorTo
	local rand
	while true do
		wait(.1)
		rand = math.random(1, #colors)
		colorTo = colors[rand]
		print("rand="..rand)

		script.Parent.BrickColor=BrickColor.new(colorTo)
		colors = {
			Color3.fromRGB(170, 64, 116),
			Color3.fromRGB(145, 86, 170),
			Color3.fromRGB(84, 95, 170),
		}
		table.remove(colors, rand)
		print(colors)
	end

The repeat is because you are redefining the table in the loop with all the colors, an easy way to prevent duplicates is to store the last color you used, an example can be found below.

local colors = {
	Color3.fromRGB(170, 64, 116),
	Color3.fromRGB(145, 86, 170),
	Color3.fromRGB(84, 95, 170),
}
local colorTo
local lastColor
local rand
while true do
	task.wait(.1)
	rand = math.random(1, #colors)
	colorTo = colors[rand]

	if colorTo ~= lastColor then
		lastColor = colorTo

		print("rand="..rand)

		script.Parent.BrickColor=BrickColor.new(colorTo)
		print(colors)
	end
end
1 Like
local function RandomColor(Part)
	local Color = Part.BrickColor
	repeat
		Part.BrickColor = BrickColor.Random()
	until Part.BrickColor ~= Color
end

local Part = Instance.new("Part")
RandomColor(Part)
print(Part.BrickColor.Name) --Earth green