Im finishing up my asset that I'm putting on the asset store. Right now one of the features require the average color of the sprite. Right now I have a public Color to find the average color, where the user can use the color picker or the color wheel or whatever to choose what they think looks like the average color of the sprite. I want to make it so the script automatically calculates the average sprite color, therefore increasing the accuracy by removing human error and increasing the efficiency by not wasting the users time guessing the average sprite color.
1 Answer
Well there is a post about it in Unity forums. Here the link. And the answer is:
Color32 AverageColorFromTexture(Texture2D tex)
{
Color32[] texColors = tex.GetPixels32();
int total = texColors.Length;
float r = 0;
float g = 0;
float b = 0;
for(int i = 0; i < total; i++)
{
r += texColors[i].r;
g += texColors[i].g;
b += texColors[i].b;
}
return new Color32((byte)(r / total) , (byte)(g / total) , (byte)(b / total) , 0);
}
-
Ok, so I tried this: TransitionColor = AverageColorFromTexture(gameObject.GetComponent<SpriteRenderer>().sprite.texture); I get an error message that the texture is not readable. Nov 12, 2015 at 2:42
-
1@user3738071 Mark the texture as readable in its settings on the Inspector in the Editor (you are going to have to switch the texture type to Advanced)– RobertoNov 12, 2015 at 4:26