Reputation: 21
I have been trying to change the color of a white sprite using script. I have the HEX valve which I convert into RGB and try to change the color of the sprite. The color gets changed but it is not exactly what I require. It changes to some random color. Below is the code which I'm Trying, I can't understand where I'm going wrong. Please Help me out. Thank You.
string tempColor;
tempColor = "E2270A";
Color m_NewColor;
float m_Red, m_Green, m_Blue;
m_Red = System.Convert.ToInt32 (tempColor.Substring (0, 2), 16);
m_Green = System.Convert.ToInt32 (tempColor.Substring (2, 2), 16);
m_Blue = System.Convert.ToInt32 (tempColor.Substring (4, 2), 16);
m_NewColor = new Color (m_Red, m_Green, m_Blue);
Animinstance.GetComponent<SpriteRenderer> ().color = m_NewColor;
Upvotes: 0
Views: 3171
Reputation: 2417
Very simply just call ColorUtility.TryParseHtmlString
api , But should add '#'
Color color;
if( ColorUtility.TryParseHtmlString("#E2270A", out color))
{
Animinstance.GetComponent<SpriteRenderer>().color = color;
}
Upvotes: 3
Reputation: 90679
As John mentioned Color
takes float
values 0.0f - 1.0f
so simply devide your values by 255f
in order to map them to the according float
(%) value .
Or you can simply use Color32
instead which takes byte
values 0-255
var tempColor = "E2270A";
var m_Red = System.Convert.ToByte(tempColor.Substring(0, 2), 16);
var m_Green = System.Convert.ToByte(tempColor.Substring(2, 2), 16);
var m_Blue = System.Convert.ToByte(tempColor.Substring(4, 2), 16);
// always requires the alpha parameter
var m_NewColor = new UnityEngine.Color32(m_Red, m_Green, m_Blue, 255);
Animinstance.GetComponent<SpriteRenderer>().color = m_NewColor;
Upvotes: 1
Reputation: 38767
If you look at the docs for Color, you'll note that the example takes float
values:
Color newColor = new Color(0.3f, 0.4f, 0.6f, 0.3f); // r, g, b, a
or
Color newColor = new Color(0.3f, 0.4f, 0.6f); // r, g, b
We can conclude from the examples that Color
expects valeus between 0 (0x00 in your hex string) and 1 (0xFF), but the integer values of these hex values are 0-255. We therefore need to divide them by 255 to get values between 0 and 1:
string tempColor;
tempColor = "E2270A";
Color m_NewColor;
float m_Red, m_Green, m_Blue;
m_Red = System.Convert.ToSingle (tempColor.Substring (0, 2), 16) / 255.0f;
m_Green = System.Convert.ToSingle (tempColor.Substring (2, 2), 16) / 255.0f;
m_Blue = System.Convert.ToSingle (tempColor.Substring (4, 2), 16) / 255.0f;
m_NewColor = new Color (m_Red, m_Green, m_Blue);
Animinstance.GetComponent<SpriteRenderer> ().color = m_NewColor;
Upvotes: 0