How to get a random, unique BrickColor

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    For my game, I want to get a random BrickColor that would be unique to every player and their buildings.

  2. What is the issue? I’m not sure how to properly check if a BrickColor is already taken, and re-roll if necessary. To note that I’m trying to keep all active colors in a folder located in ReplicatedStorage

  3. What solutions have you tried so far? I tried making 2 local functions that would check for all currently in use colors, pick a random one, and if it’s already stored in the folder, reroll; problem is, this solution requires that I call the function again from itself, which I’m not sure is possible.

Maybe there is a solution with a loop that breaks when a different one is found? But I’m not sure how to write that.

Folder where currently used colors are saved
image

The 2 functions

local function getTakenColors()
	local takenColors = {}
	for _,color in pairs(playerColors:GetChildren()) do
		table.insert(takenColors, color.Value)
	end
	
	return takenColors
end

local function getUniqueColor()
	local newColor = BrickColor.Random()
	local takenColors = getTakenColors()
	
	if takenColors[newColor] then
		getUniqueColors() -- This line errors out as I can't call a function from itself. I need another solution for this
	end
end

Thanks in advance!

Eventually figured it out with the loop.

local function getTakenColors()
	local takenColors = {}
	for _,color in pairs(playerColors:GetChildren()) do
		table.insert(takenColors, color.Value)
	end
	
	return takenColors
end

local function getUniqueColor(takenColors)
	while wait() do
		local brickColor = BrickColor.Random()
		if takenColors[brickColor] then
		else
			return brickColor
		end
	end
end

And when you need the unqiue random color, you do this:

local takenColors = getTakenColors()
playerColor.Value = getUniqueColor(takenColors)

You should recognize that BrickColor is a very limited space of colors you can get. It will be better to use Color3.new or Color3.fromHSV constructors to generate unique colors.

Also this may be better stated recursively.

local taken = {}

local function getUniqueColor()
	local color = Color3.fromHSV(math.random(), 1, 1)

	if table.find(taken, color) then 
		return getUniqueColor()
	end

	table.insert(taken, color)

	return color
end

In perfect scenario, you would also want to add the taken colors back to the probability space when you’re done with them, but frankly there is 16777216 unique RGB colors (256^3).

Though it may be important to recognize that a lot of these colors are visibly identical unless you look extremely hard. Maybe implement a color value such that it is not too close to anyone elses, so that it is at least easier to tell between two player’s colors if this is something you will be having players interact with.