Legacy Documentation: Version 5.1
LanguageEnglish
  • C#
  • JS

Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

Color.TryParseHexString

Switch to Manual
public static function TryParseHexString(hexString: string, out color: Color): bool;

Parameters

hexString Hexadecimal string to be converted into a color.
color The converted color.

Returns

bool Returns true if the operation was successful.

Description

Converts a hexadecimal string into a color.

String can be in one of the following formats:
#RGB (becomes RRGGBB)
#RRGGBB
#RGBA (becomes RRGGBBAA)
#RRGGBBAA

Note:
The '#' is optional.
Strings that are too short will be padded where rgb colors will be padded with 0 and alpha will be given full opacity(255). For example 'F' would become 'F00000FF' or 'AABBC' would become 'AABBC0FF'.


The following example creates a custom PropertyDrawer that allows the user to input hex codes for colors. This property drawer can be shown in the inspector when a color property has the attribute ColorHexPropertyAttribute.


our custom property drawer.

#pragma strict
// This is not an editor script.
public class ColorHexPropertyAttribute extends PropertyAttribute {
}
#pragma strict
// This is an editor script and should be placed in an 'Editor' directory.
@CustomPropertyDrawer(ColorHexPropertyAttribute)
public class ColorHexPropertyDrawer extends PropertyDrawer {
	public override function OnGUI(position: Rect, property: SerializedProperty, label: GUIContent) {
		var hexField: Rect = new Rect(position.x, position.y, position.width - 100, position.height);
		var colorField: Rect = new Rect(position.x + hexField.width, position.y, position.width - hexField.width, position.height);
		var hexValue: String = EditorGUI.TextField(hexField, label, "#" + property.colorValue.ToHexStringRGBA());
		var newCol: Color;
		if (Color.TryParseHexString(hexValue, newCol))
			property.colorValue = newCol;
		property.colorValue = EditorGUI.ColorField(colorField, property.colorValue);
	}
}
#pragma strict
// This shows how we would use the PropertyDrawer.
public class Example extends MonoBehaviour {
	@ColorHexProperty
	public var colorWithHex: Color = Color.green;
	public var colorWithoutHex: Color = Color.green;
}