Get The Hex String of a Color in GameMaker

Get the hex string of a color in GameMaker

Sometimes in GameMaker you may want to get the hex string of a color, especially if you’re making some kind of tool or utility rather than a game! The script we’re sharing today allows you to return a hex string of any color in code.

All colors used for drawing in GameMaker can be separated into their red, green and blue constituents, each with a value between 0 and 255.

The hex codes we use for colors are just another way of arranging this information. A color like #FF0000 (red), means 255 Red, 0 Green and 0 Blue.

Once you know these facts, it’s possible to write a script where GameMaker converts each of these values into strings and combines them together to make a single hex string. You can then show this to the user, or even allow them to copy it to their clipboard to use in other programs!

Here’s the script:

function color_to_hex_string(_color) {
	
	// Get the RGB values from 0 to 255 for the color
	var _red = color_get_red(_color);
	var _green = color_get_green(_color);
	var _blue = color_get_blue(_color);
	
	// Create a string for the hex numbers from 0 to 16
	var _hstring = "0123456789ABCDEF";
	
	var _return = "#"; // add the hash at the start of the hex string
	
	// Add the red hex values
	_return += string_char_at( _hstring, (_red div 16)+1);
	_return += string_char_at( _hstring, (_red mod 16)+1);
	
	// Add the green hex values
	_return += string_char_at( _hstring, (_green div 16)+1);
	_return += string_char_at( _hstring, (_green mod 16)+1);
	
	// Add the blue hex values
	_return += string_char_at( _hstring, (_blue div 16)+1);
	_return += string_char_at( _hstring, (_blue mod 16)+1);
	
	return _return;

}

Just be aware, GameMaker’s own color system uses BGR not RGB. So if you want red text in GameMaker you have to type “$0000FF” instead of “#FF0000”. This is the opposite of most other programs in existence, and is very annoying, but as long as you’re aware of it you shouldn’t have any problems.

If you want this script to return the color in BGR format, all you need to do is swap the sections that add the red hex values and blue hex values to the string.

Feel free to copy & paste the script from above into your own projects, or download the .yyz example below:

Daniel

I make funky little games of all different kinds like Gyro Boss, Plunder Dungeons & Spellworm! Also making lots of fonts & free game assets.

Leave a Reply