In this post, we will learn how to change/update the color of an image, text, and other 2D UI elements. Before going in-depth let’s have a brief on Unity’s Color
. In Unity 3D the Color.color having the combination of RGB with an Alpha value which is responsible for the transparency of the color.
To create a color you need four input values like
r – Red color value
g – Green color value
b – Blue color value
a – Alpha value,
these values are range between 0 – 255 on the Unity’s color picker window.
RGB vs Hexadecimal Color
RGB is a color scope of light using Red, Green, and Blue to render the colors onscreen. RGB is the primary color that provides different colors when mixed. Hexadecimal color code is similar to the RGB combination but it mentioned with the hex value of RGB input. The first two digits represent the Red color, the third and fourth digits for Green color, the last two digits represent Blue color. In most programming tools the color input will be in hexadecimal value, also it is easy to handle the color combination.
Create Color in C#
To create a new color variable do the following
When using color code in C# the input value range from 0 – 1, the method can be used without alpha value also.
The above two example are using the RGB values, we can also use the Hexadecimal color code as following.
Parse Hexadecimal Color Code
To create color from the hexadecimal value we need to use a inbuilt method to handle.
ColorUtility.TryParseHtmlString
helps to parse the hex color code to the color variable.
Create Color Variable in Unity Editor
To create a color variable from the Inspector you need to create a public variable for color.
Add pick your desire color from the color picker window.
Changing Color of UI Elements
To change the color of image, button, text and other UI elements first access the game object and update the color with new one.
Hope this post will helpful to you, Happy Coding!.