In the customization menu of a fighting game I’m helping to code, players can change the color of their armor using various UI methods - sliders, a color box, and even a hex converter.
I coded this in such a way that altering the color with any particular UI element would automatically adjust the other UI elements to match the new color I.E. repositioning the sliders, adjusting the textbox contents, etc.
The trouble arrives with the hex converter box. I can convert a hex string into a color easily enough with the following snippet:
local function fromHex(hex)
hex = hex:gsub("#","")
local r = tonumber("0x"..hex:sub(1,2))
local g = tonumber("0x"..hex:sub(3,4))
local b = tonumber("0x"..hex:sub(5,6))
return Color3.fromRGB(r, g, b)
end
However, as previously mentioned, the other elements on the panel are meant to automatically adjust themselves when you change the color via any of the methods. Thus, I’ve been experimenting with taking the newly chosen color and attempting to convert it back into a string, to no avail - roblox’s ‘tonumber’ method can convert string characters into their integer counterparts, but the process doesn’t seem to work in reverse with ‘tostring’.
Well, I did it, friends. A little research and some applied effort and I wound up with something of my own creation:
function toInteger(color)
return math.floor(color.r*255)*256^2+math.floor(color.g*255)*256+math.floor(color.b*255)
end
function toHex(color)
local int = toInteger(color)
local current = int
local final = ""
local hexChar = {
"A", "B", "C", "D", "E", "F"
}
repeat local remainder = current % 16
local char = tostring(remainder)
if remainder >= 10 then
char = hexChar[1 + remainder - 10]
end
current = math.floor(current/16)
final = final..char
until current <= 0
return "#"..string.reverse(final)
end
print(toHex(Color3.fromRGB(255, 125, 0)))
-- #FF7D00
Alternatively you can use string.format’s %02X format specifier
local function from_hex(hex: string): Color3
local r, g, b = string.match(hex, "^#?(%w%w)(%w%w)(%w%w)$")
return Color3.fromRGB(tonumber(r, 16),
tonumber(g, 16), tonumber(b, 16))
end
local function to_hex(color: Color3): string
return string.format("#%02X%02X%02X", color.R * 0xFF,
color.G * 0xFF, color.B * 0xFF)
end
There is an issue with this function. When using the Color3.fromRGB(0, 0, 0) it results in #0 which is incorrect Hex and will cause issues. So if you are going to use this function please be weary of this bug.