색상을 표현하기 위해 HEX(#000000)를 사용할 수 있습니다. 유니티에서 HEX를 RGB Color로 변환하여 사용할 수 있도록 스크립트를 작성하였습니다.

 

💬 서론

· 기본 함수

Color color;
ColorUtility.TryParseHtmlString("#60594F", out color);
mActiveOptionLabels[i].color = color;
  • 유니티의 기본 기능 중 Hex를 Color로 변환하는 코드가 이미 있습니다.
  • 하지만, 함수 매개변수가 ref out을 사용하기때문에 Color을 미리 선언하고, 참조해야하기에 불필요한 코드가 늘어납니다.

 

· 구현한 함수

mActiveOptionLabels[i].color = Utility.HexToColor("60595F");
  • 구현한 함수를 사용하면 한 줄로 간단 명료하게 표현할 수 있습니다.

 

⚒️ 구현

/// <summary>
/// Hex를 Color로 리턴합니다.
/// </summary>
/// <param name="hex">Hex (#생략 가능)</param>
/// <returns></returns>
public static Color HexToColor(string hex)
{
    hex = hex.Replace("#", ""); // "#" 문자 제거
    if (hex.Length != 6)
    {
        Debug.LogError("유효하지 않은 Hex 값입니다.");
        return Color.white;
    }

    byte r = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
    byte g = byte.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
    byte b = byte.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);

    return new Color32(r, g, b, 255);
}
  • 편리하게 접근하고 사용하기위해 static 함수로 선언하였습니다.
  • HexToColor 함수를 호출하며 string으로 HEX를 전달하면 Color로 리턴됩니다.

 

 

🕹️ Unity Affiliate

  • Unity Affiliate Program 파트너로서 아래의 배너를 통해 접속하신 경우 수수료를 받을 수 있습니다.
  • 아래 배너의 에셋들은 '실시간 무료 에셋 랭킹'을 나타냅니다.
bonnate