Tuesday, May 7, 2013

Coloring individual characters in an NGUI UILabel text

For the game project that I'm currently working on, I needed to find an easy way to color individual characters in the text of an NGUI UILabel.

Fortunately, the solution is pretty simple. When the supportEncoding boolean field on a UILabel is set to true, the text supports color encoding in the [RRGGBB] format.

This means that we can have write text such as the following (the [-] is used to revert to a previous color):

[FF0000]Red[-] [00FF00]Green[-] [0000FF]Blue[-]

The reason I needed to do this was because we want the leading zeros in the Score UILabel to have a different colour than the actual score. And for that, I wrote this neat little method to format my current score to a string with a predefined number of leading zeros and then color those leading zeros independent from the main colour of the label text.

private string FormatScore(int score, string leadingZerosRGBColor, int totalDigits)
    var scoreString = score.ToString(CultureInfo.InvariantCulture);
    var zeros = totalDigits - scoreString.Length;
    if (score == 0)
        scoreString = String.Empty;

    return String.Format("[{0}]{1}[-]{2}", leadingZerosRGBColor, new string('0', zeros <= 0 ? 0 : zeros), scoreString);

And the end result pretty much looks like our designer intended: