1+ // **************************************************************** //
2+ //
3+ // Copyright (c) RimuruDev. All rights reserved.
4+ // Contact me:
5+ // - Gmail: rimuru.dev@gmail.com
6+ // - GitHub: https://github.com/RimuruDev
7+ // - LinkedIn: https://www.linkedin.com/in/rimuru/
8+ // - GitHub Organizations: https://github.com/Rimuru-Dev
9+ //
10+ // **************************************************************** //
11+
12+ using System ;
13+ using UnityEngine ;
14+
15+ namespace External . RimuruDevUtils . Helpers . Colors
16+ {
17+ /// <summary>
18+ /// Provides utility methods for working with colors in Unity.
19+ /// This class handles conversion from hexadecimal color strings to Unity's Color objects.
20+ /// </summary>
21+ public static class ColorUtility
22+ {
23+ private const byte AlphaFull = 255 ;
24+ private const int HexadecimalMaxLength = 6 ;
25+ private const int DecimalNumberBase = 16 ;
26+
27+ /// <summary>
28+ /// Converts a hexadecimal color string to a Color object.
29+ /// </summary>
30+ /// <param name="hex">Hexadecimal string representing the color in RRGGBB format.</param>
31+ /// <returns>A Color object corresponding to the hexadecimal input. Returns white color if format is incorrect.</returns>
32+ /// <example>
33+ /// <code>
34+ /// Color myColor = ColorUtility.HexToColor("FF5733");
35+ /// </code>
36+ /// </example>
37+ public static Color HexToColor ( string hex )
38+ {
39+ if ( string . IsNullOrWhiteSpace ( hex ) || IsIncorrectFormat ( hex ) )
40+ {
41+ Debug . LogWarning ( "Invalid or empty hexadecimal string. Returning white color." ) ;
42+ return Color . white ;
43+ }
44+
45+ try
46+ {
47+ var red = Convert . ToInt32 ( hex . Substring ( 0 , 2 ) , DecimalNumberBase ) ;
48+ var green = Convert . ToInt32 ( hex . Substring ( 2 , 2 ) , DecimalNumberBase ) ;
49+ var blue = Convert . ToInt32 ( hex . Substring ( 4 , 2 ) , DecimalNumberBase ) ;
50+
51+ return new Color32 ( ( byte ) red , ( byte ) green , ( byte ) blue , AlphaFull ) ;
52+ }
53+ catch ( Exception ex )
54+ {
55+ Debug . LogError ( $ "Error converting hex to color: { ex . Message } ") ;
56+ return Color . white ;
57+ }
58+ }
59+
60+ /// <summary>
61+ /// Checks if the provided hexadecimal string has an incorrect format.
62+ /// </summary>
63+ /// <param name="hex">Hexadecimal string to check.</param>
64+ /// <returns>True if the format is incorrect, otherwise false.</returns>
65+ private static bool IsIncorrectFormat ( string hex )
66+ {
67+ return hex . Length != HexadecimalMaxLength ;
68+ }
69+ }
70+ }
0 commit comments